绑定风格二传手到公共财产?

时间:2011-05-21 19:55:04

标签: c# .net wpf xaml

我想将样式中的Fill属性绑定到公共属性,我使用了以下方法,但似乎它不起作用。

public SevenSegmentControl()
{
    InitializeComponent();
    SevenSegmentColor = Color.FromRgb(251, 23, 23);
}

public Color SevenSegmentColor { get; set; }
<Style x:Key="RectangleStyle1" TargetType="{x:Type Rectangle}">
    <Setter Property="Fill" Value="{Binding Path=SevenSegmentColor, Mode=TwoWay}"/>
    <Setter Property="RadiusX" Value="4"/>
    <Setter Property="RadiusY" Value="4"/>
    <Setter Property="StrokeThickness" Value="0"/>
    <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
</Style>

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您正在尝试将颜色值直接设置为Fill属性,该属性为Brush类型。您可以检查“输出”窗口以找出binding errors。您需要{{3}将颜色转换为有效的画笔,或者你需要这样做

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SevenSegmentColor =new SolidColorBrush(Color.FromRgb(251, 23, 23));
            DataContext=this;
        }

        public SolidColorBrush SevenSegmentColor { get; set; }

    }

修改

如果在设置属性值之前分配Datacontext,则永远不会在您的属性更改中通知UI。在您的情况下,您将使用

分配datacontext
DataContext="{Binding RelativeSource={RelativeSource Self}}"

因此,在为SevenSegmentColor属性赋值之前,Datacontext是在初始化时设置的。在初始化之后,当您为属性指定了颜色值时,UI将永远不会得到通知,因此您的颜色是UI中没有显示。要解决此问题,您需要在UserControl中实现valueconverter接口

<强>示例

 /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        private SolidColorBrush sevenSegmentColor;
        public MainWindow()
        { 
            InitializeComponent();
           SevenSegmentColor =new SolidColorBrush(Color.FromRgb(251, 23, 23));
        }

        public SolidColorBrush SevenSegmentColor
        {
            get
            {
                return sevenSegmentColor;
            }
            set
            {
                sevenSegmentColor = value;
                // Call OnPropertyChanged whenever the property is updated
                OnPropertyChanged("SevenSegmentColor");
            }
        }

        // Declare the event
        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event
        public void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }