【问题标题】:Color of border based on domain model?基于域模型的边框颜色?
【发布时间】:2011-10-15 23:11:53
【问题描述】:

我的域模型中有一个 poco 类:

public class Slot
{
    bool HasPlayed { get; set; }
}

我在列表框项目模板中显示它。

<Border Background="...">
    <CheckBox IsChecked="{Binding Path=HasPlayed, Mode=TwoWay}" />
</Border>

但我想做的是当 HasPlayed 为真时,边框的背景颜色变为红色,当为假时为绿色。这些画笔在资源字典中。

我可以在域模型中添加一个 Brush,但这会破坏关注点的分离。我以后也不会使用复选框,这只是一个模拟 UI。

我尝试了 IValueConverter,但它不会在属性更改时更改。该模型确实实现了 INotifyPropertyChanged。

当属性改变时你会如何改变颜色?

【问题讨论】:

  • 您的 IValueConverter 代码是什么样的?
  • 它最初为边框着色,但是当属性发生更改时,它不会更新。

标签: c# wpf domain-model


【解决方案1】:

【讨论】:

    【解决方案2】:

    我猜测属性更改没有被拾取,因为 Slot 没有实现 INotifyPropertyChanged。

    试试这样的:

    public class Slot : INotifyPropertyChanged
        {
            private bool _hasPlayed;
    
            private bool HasPlayed
            {
                get { return _hasPlayed; }
                set
                {
                    _hasPlayed = value;
                    InvokePropertyChanged(new PropertyChangedEventArgs("HasPlayed"));
                }
            }
    
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
    
            public void InvokePropertyChanged(PropertyChangedEventArgs e)
            {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, e);
                }
            }
        }
    

    【讨论】:

    • 它确实实现了 INotifyPropertyChanged。
    【解决方案3】:

    您传递给转换器的值似乎是Slot,因此绑定不指向更改的属性,以便绑定更新但是绑定需要指定指向相关属性的路径,在这种情况下HasPlayed。 (而拥有该属性的对象当然需要实现INPC,但你说已经是这样了,对吧?)

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2023-03-08
      • 2020-07-18
      • 2021-11-01
      • 2020-01-17
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多