TextBox's Text set through DataTrigger not updating the property value in Model

流过昼夜 提交于 2019-12-23 12:25:11

问题


I am new to WPF and I want to clear a textBox's value if a check box is unchecked. I tried doing that through data triggers.

Below is the code:

<TextBox Text="{Binding Path=Amount,Mode=TwoWay}">
                    <TextBox.Style>
                        <Style>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=IsSelected}" Value="false">
                                    <Setter Property="TextBox.Text" Value="{x:Null}"></Setter>
                                </DataTrigger>  
                            </Style.Triggers>
                        </Style>
                    </TextBox.Style>
                </TextBox> 

My checkbox's value is set in "IsSelected" property of My Model. Here, if the checkbox is unchecked, then the text's updated value, which is {x:Null} in this case, is not reflecting in "Amount" property of my Model. Because of this the text never seems to be changed on the UI. The "Amount" earlier set value is getting set again in the TextBox because of binding

Any help is appreciated. Let me know in case you need any more information or clarification Thanks.


回答1:


In such cases I normally prefer ViewModel / Model doing the "clear" part of the functionality,

hence in your case I'd normally do something like:

public bool IsSelected {
  get {
    return _isSelected;
  }

  private set {
    if (value == _isSelected)
      return;

    RaisePropertyChanging(() => IsSelected);
    _isSelected = value;
    RaisePropertyChanged(() => IsSelected);

    if (_isSelected == false)
      Amount = string.Empty
  }
}

That way the View does not hold responsibility for any logic and thus doesn't need the DataTrigger at all

Update:

The Problem with your code is when you set the Text with a Binding in the TextBox it takes precedence over the value you set in the Style for the Text property. You can check this by using this:

<TextBox>
  <TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="Text"
              Value="{Binding Path=Amount,
                              Mode=TwoWay}" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsSelected}"
                      Value="false">
          <Setter Property="Text"
                  Value="{x:Null}" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBox.Style>
</TextBox>

This will now clear the Text when the CheckBox is checked, however it will not be updating your Binding(Amount) since essentially your Binding is only active when the CheckBox is selected.



来源:https://stackoverflow.com/questions/16397570/textboxs-text-set-through-datatrigger-not-updating-the-property-value-in-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!