【发布时间】:2022-01-02 06:02:04
【问题描述】:
我想以编程方式更改自定义依赖属性的值。
这是我的 XAML:
<Window.Resources>
<ResourceDictionary>
<Style
x:Key="TreeViewItemStyle"
TargetType="TreeViewItem">
<Style.Triggers>
<Trigger
Property="local:ColorHelper.IsColor"
Value="True" >
<Setter
Property="Foreground"
Value="{Binding Color}" />
</Trigger>
<Trigger
Property="local:ColorHelper.IsColor"
Value="False" >
<Setter
Property="Foreground"
Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Window.Resources>
我希望将此样式应用于树视图
<TreeView
HorizontalAlignment="Stretch"
Margin="15,65,15,0"
x:Name="treeView1"
VerticalAlignment="Stretch"
ItemContainerStyle="{StaticResource TreeViewItemStyle}"
ItemTemplate="{StaticResource CheckBoxItemTemplate}"
Grid.ColumnSpan="1"
Grid.RowSpan="2"
Grid.Column="1" />
并通过复选框更改 IsColor 属性的颜色值:
<CheckBox
Name="CHK_Gray"
VerticalAlignment="Center"
Foreground="DarkGray"
Grid.Row="6"
Grid.Column="0"
Grid.RowSpan="1"
Grid.ColumnSpan="2"
Unchecked="grayCheckBox_Unchecked"
Checked="grayCheckBox_Checked">
Show Created Assembly (in Grey)
</CheckBox>
依赖属性是这样创建的:
public class ColorHelper : DependencyObject
{
public static readonly DependencyProperty IsColorProperty = DependencyProperty.Register(
"IsColor", typeof(bool), typeof(ColorHelper), new PropertyMetadata(false));
public static void SetIsColor(DependencyObject target, Boolean value)
{
target.SetValue(IsColorProperty, value);
}
public static bool GetIsColor(DependencyObject target)
{
return (bool)target.GetValue(IsColorProperty);
}
}
如何在 Checked 和 Unchecked 事件中更改 IsColor 属性的值?
private void grayCheckBox_Checked(object sender, RoutedEventArgs e)
{
???
}
private void grayCheckBox_Unchecked(object sender, RoutedEventArgs e)
{
???
}
非常感谢您的帮助!
【问题讨论】:
-
你为什么在这个任务中使用代码隐藏?使用触发器
<Style.Triggers><Trigger Property="IsChecked" Value="True"><Setter Property="Foreground" Value="Black"/></Trigger> <Trigger Property="IsChecked" Value="False"><Setter Property="Foreground" Value="{DynamicResource MyColor}"/></Trigger> -
Foreground 属性用于 TreeView 而 CheckBox 是外部的
-
在这种情况下创建一个合适的minimal reproducible example
-
@ASh 我修改了这个问题,因为我正在尝试遵循您的建议并使用触发器。我希望有所有需要的信息。你能帮我解决这个问题吗..?非常感谢
标签: c# wpf data-binding