<!-- View -->
<TextBox Text="{Binding str, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
// View Model
private string _str;
public string str
{
get { return _str; }
set
{
if (!value.Contains("a"))
_str = value;
OnPropertyChanged(nameof(str));
}
}
Run Code Online (Sandbox Code Playgroud)
在TextBox中输入时,我希望它抛出任何无效字符(在这个示例中,字母'a',但它可能真的适用于任何东西).例如:
在UWP中,当控件具有焦点时,它似乎不会尊重TwoWay绑定.
我可以创建一个具有Click事件的按钮,按下该事件时将正确更新我的TextBox.
private void btn_Click(object sender, RoutedEventArgs e)
{
OnPropertyChanged(nameof(str));
}
Run Code Online (Sandbox Code Playgroud)
我们需要在WPF和UWP视图中使用许多ViewModel,并且我们在所有地方都有这种必需的行为.什么是这个问题的好方法?
*编辑*
周末之后又回到了问题,似乎已经解决了问题.我不知道为什么.我现在正在结束这个问题.
您可以使用转换器来解决您的问题,您可以精心设计一个更好的转换器,在我的示例中,我只是使用一个愚蠢的转换器来演示我的想法。
转换器:
public class Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var someString = value.ToString();
return someString.Replace("a", "");
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
XAML
<TextBox Text="{Binding Str, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource converter}}"/>
Run Code Online (Sandbox Code Playgroud)
您也可以使用附加行为。