2009-06-30 19 views
0

我的意思是这个。为了测试我需要当用户检CHK1CHK2元素更改属性的IsEnabled但我不能这样做参考CHK2元素以风格调用WPF树中的其他元素

这是款式XAML。

<Style x:Key="styleCheckBox" TargetType="{x:Type CheckBox}"> 
      <Style.Triggers> 
       <Trigger Property="IsChecked" Value="True"> 

      </Style.Triggers> 
</Style 

电话样式..

<StackPanel> 
     <CheckBox x:Name="chk1" Content="CheckBox1" Style="{StaticResource styleCheckBox}"/> 
     <CheckBox x:Name="chk2" Content="CheckBox2"/> 
    </StackPanel> 

回答

3

您不能在样式触发设置TargetProperty。这基本上意味着你应该创建一个派生自StackPanel的自定义控件,其中包含两个复选框,并且这些复选框显示为属性。然后你就可以为该控件定义一个样式(不是CheckBox)并设置你想要的属性。

更简单的方法(如果只需要测试)会是这样:

<StackPanel> 
<StackPanel.Resources> 
    <local:InverseBoolConverter x:Key="InverseBoolConverter"/> 
</StackPanel.Resources> 
<CheckBox x:Name="chk1" Content="CheckBox1"/> 
<CheckBox x:Name="chk2" Content="CheckBox2" IsEnabled="{Binding ElementName=chk1, Path=IsChecked, Converter={StaticResource InverseBoolConverter}}"/> 
</StackPanel> 

凡InverseBoolConverter定义如下:

[ValueConversion(typeof(bool), typeof(bool))] 
public class InverseBoolConverter: IValueConverter { 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 
     if(value is bool) 
      return !(bool)value; 
     else 
      return null; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 
     if(value is bool) 
      return !(bool)value; 
     else 
      return null; 
    } 
} 
+0

谢谢!,是非常有用的。 – Rangel 2009-06-30 08:44:19