如何将属性触发器与用户控件上的依赖项属性一起使用?



如何将属性触发器与用户控件上的依赖项属性结合使用,以按名称设置 UI 元素的样式属性?

我有一个自定义用户控件,MyUserControl.xaml

<UserControl x:Class="MyProject.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Triggers>
<Trigger Property="IsEditable" Value="True">
<Setter Property="Visibility" Value="Collapsed" TargetName="NameField" />
<Setter Property="Visibility" Value="Visible" TargetName="NameBox" />
</Trigger>
<Trigger Property="IsEditable" Value="False">
<Setter Property="Visibility" Value="Collapsed" TargetName="NameBox" />
<Setter Property="Visibility" Value="Visible" TargetName="NameField" />
</Trigger>
</UserControl.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Name" />
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="NameField" Text="{Binding Name}" />
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="NameBox" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</UserControl>

而代码隐藏MyUserControl.xaml.cs

using System.Windows;
namespace MyProject
{
public partial class MyUserControl
{
public bool IsEditable
{
get { return (bool)GetValue(IsEditableProperty); }
set { SetValue(IsEditableProperty, value); }
}
public static readonly DependencyProperty IsEditableProperty =
DependencyProperty.Register("IsEditable", typeof(bool),
typeof(MyUserControl), new PropertyMetadata(false));
public UserDetailedUserControl()
{
InitializeComponent();
}
}
}

我像这样将其包含在我的主窗口中:

<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<local:MyUserControl />
</Window>

我的目的是能够像这样包含它:

<local:MyUserControl IsEditable="True" />

并获取TextBox而不是TextBlock.

编译时,在 XAML 中出现错误:

"IsEditable"成员无效,因为它没有限定类型名称。 (MyUserControl.xaml 第 9 行(

我相信我需要对我的Value属性做一些事情,将它们设置为文字布尔truefalse,而不是字符串"True"和"False",但我不确定该怎么做。

编辑

安迪在评论中建议:

类似于 Property="local:MyUserControl.IsEditable",其中 local 是 MyProject 的 xmlns

当我这样做时,我在同一行上收到不同的错误,"Unkown 构建错误:键不能为空"。

我认为这是在正确的轨道上,但语法不太正确......在不使用大括号的情况下将命名空间放在 XAML 参数值中似乎是错误的。

我会使用 DataTriggers 而不是标准触发器,以便您可以将绑定显式设置为触发器中代码隐藏的 IsEditable 属性。

最新更新