是否有可能在不实现INotifyPropertyChanged
接口的情况下更新文本框,例如,使用我的ViewModel中的触发器或事件?
我的示例代码
用户控制:
<StackPanel VerticalAlignment="Center">
<TextBox Text="{Binding Model.ExampleClass.MyProperty, Mode=TwoWay}" Height="20" Width="400"/>
<TextBox Text="{Binding Model.TestProperty, Mode=TwoWay}" Height="20" Width="400"/>
</StackPanel>
<Button Command="{Binding ButtonClickCommand}" Grid.Row="1" Content="Click" Height="40"/>
ViewModel:
private Model _model = new Model();
public Model Model
{
get { return _model; }
set { SetProperty(ref _model, value); }
}
public ICommand ButtonClickCommand { get; private set; }
public ViewModel()
{
ButtonClickCommand = new RelayCommand(ButtonClickExecute, ButtonClickCanExecute);
}
#region ICommand
private bool ButtonClickCanExecute(object obj)
{
return true;
}
private void ButtonClickExecute(object obj)
{
Model.ExampleClass.MyProperty = 50;
Model.TestProperty = 50;
}
#endregion
型号:
private ExampleClass _exampleClass = new ExampleClass() { MyProperty = 30};
private int _testProperty = 30;
public ExampleClass ExampleClass
{
get { return _exampleClass; }
set { SetProperty(ref _exampleClass, value); }
}
public int TestProperty
{
get { return _testProperty; }
set { SetProperty(ref _testProperty, value); }
}
ExampleClass(无法更改(:
public class ExampleClass
{
public int MyProperty { get; set; }
}
我的问题
我想通过单击按钮来更新ExampleClass
中的属性MyProperty
(不需要实现INotifyPropertyChanged
,也不需要对类进行任何其他更改(。
您可以尝试获取TextBox.TextPropery的绑定表达式并手动触发更新。示例:textBox1.GetBindingExpression(TextBox.TextProperty).UpdateTarget();