WPF C#设置触发器属性,由后面的代码控制

时间:2012-07-24 04:40:42

标签: c# wpf visual-studio-2010 wpf-controls contentcontrol

<ContentControl Width="130"
                Height="130"
                Canvas.Top="60"
                Canvas.Left="50"
                ***Selector.IsSelected="True"***
                Style="{StaticResource DesignerItemStyle}">

我想通过使用后面的代码将属性Selector.IsSelected设置为ContentControl。但我不知道该怎么做。请帮帮我,给我一些例子。

2 个答案:

答案 0 :(得分:3)

如果要在代码中设置附加依赖项属性,请执行此操作

        ContentControl x;
        //To set the value
        x.SetValue(Selector.IsSelectedProperty, true);

        //To Clear the value
        x.ClearValue(Selector.IsSelectedProperty);

        //Set using the static function on Selector
        Selector.SetIsSelected(x, true);

答案 1 :(得分:2)

要访问代码隐藏中的控件,首先需要为其提供一个名称 -

<ContentControl 
    x:Name=""ContentControl1"
    Width="130" 
    Height="130" 
    Canvas.Top="60" 
    Canvas.Left="50" 
    ***Selector.IsSelected="True"*** 
    Style="{StaticResource DesignerItemStyle}"> 

然后你可以在代码中访问它并设置其他答案中提到的值 -

ContentControl1.SetValue(Selector.IsSelectedProperty, true);

除此之外,最好是在代码隐藏或ViewModel(MVVM)中创建属性并将其直接绑定到您的控件 -

<ContentControl 
    Width="130" 
    Height="130" 
    Canvas.Top="60" 
    Canvas.Left="50" 
    Selector.IsSelected="{Binding IsSelectedBoolProperty, Mode=OneWay}"
    Style="{StaticResource DesignerItemStyle}"> 

如果您的窗口中有很多控件,这种技术将非常有用,我建议您在应用程序中实现MVVM,以避免在代码隐藏中执行这些操作。