我正在使用VS 2015编写WPF应用程序。 在我的窗口中,我有一个TextBox和一个ToggleButton,用于在FontWeights.Bold和FontWeights.Normal之间切换。 在我的ViewModel中,我有两个属性。一个用于ToggleButton的IsChecked属性,另一个用于TextBox的FontWeight。
/// <summary>
/// Gets or sets if the button setFontBold is checked.
/// </summary>
private bool? setFontBoldIsChecked = false;
public bool? SetFontBoldIsChecked
{
get { return setFontBoldIsChecked; }
set
{
setFontBoldIsChecked = value;
RaisePropertyChanged("SetFontBoldIsChecked");
RaisePropertyChanged("TextFontWeight");
}
}
/// <summary>
/// Gets the fontweight depending on SetFontBoldIsChecked.
/// </summary>
public FontWeight TextFontWeight
{
get { return (setFontBoldIsChecked == true) ? FontWeights.Bold : FontWeights.Normal; }
}
TextBox的FontWeight属性绑定如下:
<TextBox x:Name="textbox1" FontWeight="{Binding TextFontWeight}"/>
ToggleButton的IsChecked属性绑定到SetFontBoldIsChecked:
<ToggleButton x:Name="setFontBold" IsChecked="{Binding SetFontBoldIsChecked}"/>
当我启动应用程序并单击ToggleButton时,IsEnabled为true,文本显示为粗体。 但是,如果我再试一次,RaisePropertyChanged(“TextFontWeight”)不会调用TextFontWeight的Getter。
为什么会这样?
提前致谢! 帕特里克
答案 0 :(得分:0)
感谢一位同事,我发现了它! 在XAML中,必须设置所有属性:
<TextBox x:Name="textForTextProperty" FontWeight="{Binding TextFontWeight, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
视图模型中的属性必须稍微更改一下:
/// <summary>
/// Gets or sets if the button setFontBold is checked.
/// </summary>
private bool? setFontBoldIsChecked = false;
public bool? SetFontBoldIsChecked
{
get { return setFontBoldIsChecked; }
set
{
setFontBoldIsChecked = value;
RaisePropertyChanged("SetFontBoldIsChecked");
RaisePropertyChanged("TextFontWeight");
}
}
/// <summary>
/// Gets the fontweight depending on SetFontBoldIsChecked.
/// </summary>
private FontWeight textFontWeight;
public FontWeight TextFontWeight
{
//get { return textFontWeight; }
get
{
textFontWeight = (SetFontBoldIsChecked == true) ? FontWeights.Bold : FontWeights.Normal;
return textFontWeight;
}
set
{
textFontWeight = value;
RaisePropertyChanged("TextFontWeight");
}
}
现在可行。