【问题标题】:WPF Radio button value and the label textWPF 单选按钮值和标签文本
【发布时间】:2015-12-22 12:43:30
【问题描述】:

我正在尝试将标签文本与单选按钮值相关联,例如如果选中 radio,则标签文本为“x”。如果不是,则为“y”。 在我的 XML 中:

<RadioButton x:Name="radio1" Content="Option1" GroupName="Group1" IsChecked="{Binding BoolValue, Converter={StaticResource BooleanConverter}, ConverterParameter='true', Mode=TwoWay}" />
<RadioButton Content="Option2" GroupName="Group2" IsChecked="{Binding BoolValue, Converter={StaticResource BooleanConverter}, ConverterParameter='false', Mode=TwoWay}"/>
...
...
<Label Content="{Binding LabelText, UpdateSourceTrigger=PropertyChanged}" Width="70"/>

在代码中: (_shape 绑定到单选按钮 IsChecked;)

private bool _boolValue;
public bool BoolValue
{
    get { return _boolValue; }
    set
    {
        _boolValue= value;
        PackLengthLabel = (_boolValue == true)? "x" : "y";
        OnPropertyChanged("BoolValue");
    }
}

以及标签文本属性:

private string _labelText;
public string LabelText
{
    get { return _labelText; }
    set
    {
        _labelText = value;
        OnPropertyChanged("LabelText");
    }
}

问题在于更改不会影响标签文本 - 无论选中哪个复选框,它始终相同。布尔值和文本值正在改变(在设置器中检查)。我还检查了标签是否试图从 getter 获取 _labelText 但它没有。我也尝试了不同的绑定模式,但文字都是一样的。 它影响其他控件的唯一方法是直接绑定到其他属性,例如:

IsEnabled="{Binding IsChecked, ElementName=radio1}" 

编辑1:

我可以通过两种方式让它工作:

  1. 在后面的View代码中设置标签内容值,参考元素属性

  2. 在此处使用代码:https://stackoverflow.com/a/23642108/3974198

但我还是很好奇,为什么标签文本值的简单 getter 和 setter 不起作用。

【问题讨论】:

  • 您的 BooleanConverter 是在哪里定义的?你也可以上传那段代码吗?
  • 这里是代码:pasted.co/6dd634db
  • 所以我在实现的目的上有点挣扎。如果我理解正确,您希望始终选中“x”,但它可能是单选按钮 1 或单选按钮 2。但我认为可能对您有所帮助的是做一些关注点分离。 “X”、“Y”是您要存储的实际数据值,还是您确实试图将布尔值存储为您的数据类型?
  • 我想我要说的是,如果尝试使用 MVVM,IValueConverters 真的是为了“视觉”表示,因为它们通常位于您的视图中。你似乎真的想在你的数据/模型中记录 X、Y?
  • 我有一个样本,我回复了here

标签: mvvm radio-button label


【解决方案1】:

我终于明白了。我在 View 和 ViewModel 中有属性设置器和获取器。问题是 View 继承自 INotifyPropertyChanged,但 ViewModel 没有在 ViewModel 中,我可以使用 OnPropertyChanged,而不会出现任何错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 2013-04-25
    • 2018-05-29
    • 2012-10-16
    • 2012-01-07
    • 2013-07-20
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多