我有一个简单的WinRT(Win8,.NET / C#/ XAML)项目。我的一个XAML TextBox控件附加了一个自定义StringValueConverter,它根据View Model格式化数据绑定值。
这很好用,但它缺少一件事:当用户更改TextBox中的值(例如:货币值)并离开TextBox时,应自动应用转换器。到目前为止,视图模型中的数据绑定值已更新,但视图不会再次应用转换器。
是否有针对此或任何已知自定义解决方案的内置解决方案?
答案 0 :(得分:0)
我测试了您描述的场景并且工作正常:
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));
}
}
}
}
ValueConverter:
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方法,而不是转换方法。
你确定你的装订工作正常吗?