0

Is there a possibility to update a textbox without implementation of the INotifyPropertyChanged interface, e.g. with a trigger or an event from my ViewModel?

My example Code

UserControl:

<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

Model:

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 (cannot be changed):

public class ExampleClass
{
    public int MyProperty { get; set; }
}

My Problem

I want to update my property MyProperty in my ExampleClass by a button click (without implementation of INotifyPropertyChanged or that I need to make any other changes to the class).

Alex
  • 21
  • 1
  • 1
  • 5
  • 1
    `Model.ExampleClass = new ExampleClass { MyProperty = 50 };` would work. – Clemens Oct 29 '20 at 10:26
  • Does this answer your question? [How to force a WPF binding to refresh?](https://stackoverflow.com/questions/5676202/how-to-force-a-wpf-binding-to-refresh) – Sinatr Oct 29 '20 at 10:36
  • @Clemens But if I have several properties and I only want to change one of them, I always have to pass all of them. – Alex Oct 29 '20 at 10:39
  • 2
    Then write `var x = Model.ExampleClass; Model.ExampleClass = null; x.MyProperty = 50; Model.ExampleClass = x;` – Clemens Oct 29 '20 at 10:41
  • @Sinatr how can i implement this in my ViewModel? – Alex Oct 29 '20 at 11:20
  • @Alex You can't explictly refresh a Binding by the mentioned solution in a view model. The view model (and IMO even the view's code behind) should not have knowledge of any Bindings. What if multiple UI elements bind to a single model property? – Clemens Oct 29 '20 at 11:23

1 Answers1

0

You can try to get binding expression for TextBox.TextPropery and manually trigger update. Example: textBox1.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

Volodymyr Baydalka
  • 3,635
  • 1
  • 12
  • 13