【问题标题】:RaisePropertyChanged of dependent property is called only once依赖属性的 RaisePropertyChanged 仅被调用一次
【发布时间】:2016-04-18 15:17:23
【问题描述】:

我正在使用 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。

为什么会这样?

提前致谢! 帕特里克

【问题讨论】:

  • 这对我有用。一定有什么你没有给我们看的。
  • 也许问题如下:我有一个主窗口,我从工具箱中拖放控件(如标签)。使用 ToggleButton 放下属性设置窗口后,打开 TextBox(用于预览)。在我调整属性并在 TextBox 中看到结果后,我确认它并且窗口没有关闭而是使用 Hide-command 隐藏。在隐藏窗口之前,我将 ViewModel 中的所有属性重置为默认值。这意味着 SetFontBoldIsChecked=false。当我放下下一个控件时,设置窗口再次出现,并且 Raise 不会触发 TextFontWeight 的 Getter。

标签: c# wpf


【解决方案1】:

感谢一位同事,我找到了! 在 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");
    }
}

现在可以了。

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2014-08-06
    • 2012-10-05
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多