【问题标题】:Update binding without implementation of INotifyPropertyChanged?在没有实现 INotifyPropertyChanged 的​​情况下更新绑定?
【发布时间】:2021-02-11 18:38:05
【问题描述】:

是否有可能在不实现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"/>

视图模型:

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 或者我需要对类进行任何其他更改)。

【问题讨论】:

  • Model.ExampleClass = new ExampleClass { MyProperty = 50 }; 可以。
  • 这能回答你的问题吗? How to force a WPF binding to refresh?
  • @Clemens 但是如果我有几个属性并且我只想更改其中一个,我总是必须通过所有属性。
  • 然后写var x = Model.ExampleClass; Model.ExampleClass = null; x.MyProperty = 50; Model.ExampleClass = x;
  • @Sinatr 我如何在我的 ViewModel 中实现它?

标签: c# wpf mvvm inotifypropertychanged


【解决方案1】:

您可以尝试获取 TextBox.TextPropery 的绑定表达式并手动触发更新。例子: textBox1.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 2017-04-19
    • 2014-10-20
    • 1970-01-01
    • 2011-09-02
    相关资源
    最近更新 更多