通过代码中的样式设置背景属性不起作用,但直接设置它

时间:2016-08-04 10:07:50

标签: wpf telerik radgridview

我试图为边框的背景颜色设置一种风格,奇怪的是,如果我这样做就可以了:

var borders = this.Editor.ChildrenOfType<Border>().Where(x => x.Name == "Background_Selected");
foreach (var border in borders)
{
    border.Background = Brushes.Red;
}

但我希望(需要)这样做:

var borders = this.Editor.ChildrenOfType<Border>().Where(x => x.Name == "Background_Selected");
foreach (var border in borders)
{
    var style = new Style(typeof(Border));
    style.Setters.Add(new Setter()
    {
        Property = BackgroundProperty,
        Value = Brushes.Red
    });

    border.Style = style;
}

这里发生了什么?为什么我不能用风格设置它,但可以直接设置它。

修改

我需要这样做的原因是因为我想根据绑定对象的值设置此背景颜色(我计划设置为这样):

var borders = this.Editor.ChildrenOfType<Border>().Where(x => x.Name == "Background_Selected");
foreach (var border in borders)
{
    var binding = new Binding();
    binding.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent);
    binding.Path = new PropertyPath("Value.IsSelected");
    binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

    var style = new Style(typeof(Border));
    var trigger1 = new DataTrigger()
    {
        Binding = binding,
        Value = true
    };

    trigger1.Setters.Add(new Setter()
    {
        Property = BackgroundProperty,
        Value = Brushes.Green
    });

    var trigger2 = new DataTrigger()
    {
        Binding = binding,
        Value = false
    };

    trigger2.Setters.Add(new Setter()
    {
        Property = BackgroundProperty,
        Value = Brushes.Red
    });

    style.Triggers.Add(trigger1);
    style.Triggers.Add(trigger2);

    border.Style = style;
}

0 个答案:

没有答案