【问题标题】:Apply Value Converter on changed value in TextBox对文本框中更改的值应用值转换器
【发布时间】:2013-03-06 11:11:55
【问题描述】:

我有一个简单的 WinRT(Win8、.NET/C#/XAML)项目。我的 XAML TextBox 控件之一附加了一个自定义 StringValueConverter,它格式化来自视图模型的数据绑定值。

这很好用,但它缺少一件事:当用户更改 TextBox 中的值(例如:货币值)并离开 TextBox 时,应自动应用转换器。到目前为止,View Model 中的数据绑定值已更新,但 View 并未再次应用转换器。

是否有任何内置解决方案或任何已知的自定义解决方案?

【问题讨论】:

  • 您的 ViewModel(我假设是您的 DataContext)是否继承自 BindableBase 类(或以其他方式实现 INotifyPropertyChanged 类)?您必须通知 UI 该值已更改。
  • 这不是很奇怪吗?当用户更改 UI 上的值时,为什么我必须再次从 View Model 触发 UI 来更新(格式化)值? (逻辑上)对我来说没有多大意义。当然,视图模型(或绑定的数据项)实现了 INotifyPropertyChanged。否则,整个数据绑定将无法正常工作。

标签: xaml data-binding windows-8 winrt-xaml ivalueconverter


【解决方案1】:

我测试了你描述的场景,它工作正常:

XAML:

<Window x:Class="ValueConverterTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:valueConverterTest="clr-namespace:ValueConverterTest"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <valueConverterTest:CustomConverter x:Key="CustomConverter" />
</Window.Resources>
  <StackPanel>
   <TextBox Text="{Binding CustomText, Converter={StaticResource CustomConverter}}"></TextBox>
    <TextBox></TextBox>
</StackPanel>
</Window>

后面的代码:

namespace ValueConverterTest
{
   using System.ComponentModel;
   using System.Windows;

   public partial class MainWindow : Window, INotifyPropertyChanged 
   {

      public string CustomText
      {
        get { return customText; }
        set
        {
           customText = value;
           OnPropertyChanged("CustomText");
        }
      }

      public MainWindow()
      {
        InitializeComponent();
        DataContext = this;
      }

      private string customText;

      public event PropertyChangedEventHandler PropertyChanged;

      protected virtual void OnPropertyChanged(string propertyName)
      {
         PropertyChangedEventHandler handler = PropertyChanged;
         if (handler != null)
         {
            handler(this, new PropertyChangedEventArgs(propertyName));
         }
      }
   }
}

值转换器:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ValueConverterTest
{
   public class CustomConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         return value;
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         return value;
      }
   }
}

此示例运行良好。通过首先离开文本框,调用 convert back 方法,然后再调用 convert 方法。

您确定您的绑定工作正常吗?

【讨论】:

  • 您确定这是一个有效的 WinRT XAML 示例吗?对我来说看起来更像 WPF...而且不:这个简单的示例(为 WinRT 采用)不适用于 Windows Store App 项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
相关资源
最近更新 更多