【发布时间】:2017-07-25 16:08:34
【问题描述】:
我有一个UserControl,它有两个自定义属性CustomA 和CustomB。我想在UserControl 内的Label 控件中使用DataTriggers,以更改这些自定义属性的Value。
在我的示例中,我似乎无法或不知道如何访问 Setter 中的 CustomB 属性,因此当CustomA 属性的 Value 时,我可以将其更改为 Value数据触发器的变化。我认为 CustomA 属性的绑定是正确的,但我不知道 Setter 使用什么来访问 CustomB。
总而言之,我需要知道如何从控件的样式 DataTriggers 中访问属于我的 UserControl 的自定义属性 - 在本例中为 Label - 并更改它们的值
UCLabel.xaml - 用户控件
<UserControl x:Class="UCLabel"
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"
xmlns:local="clr-namespace:TestProgram"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="100">
<Label Name="lbl">
<Label.Style>
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=CustomA}" Value="True">
<Setter Property="CustomB" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
</UserControl>
UCLabel.xaml.vb - 代码隐藏
Imports System.Windows
Public Class UCLabel
'CustomA'
Public Shared ReadOnly CustomAProperty As DependencyProperty =
DependencyProperty.Register("CustomA",
GetType(Boolean),
GetType(UCLabel), New PropertyMetadata(False))
Public Property CustomA As Boolean
Get
Return CBool(GetValue(CustomAProperty))
End Get
Set(ByVal value As Boolean)
SetValue(CustomAProperty, value)
End Set
End Property
'CustomB'
Public Shared ReadOnly CustomBProperty As DependencyProperty =
DependencyProperty.Register("CustomB",
GetType(Boolean),
GetType(UCLabel), New PropertyMetadata(False))
Public Property CustomB As Boolean
Get
Return CBool(GetValue(CustomBProperty))
End Get
Set(ByVal value As Boolean)
SetValue(CustomBProperty, value)
End Set
End Property
End Class
【问题讨论】:
-
我认为你需要更现实一些。您可以在代码中简单地将这两个属性与转换器绑定。您甚至可能不需要两个属性。
-
是的,我想知道是否可以这样做!通过转换器,您的意思是当 Convert/ConvertBack 方法中 CustomA 属性的值发生变化时,我也应该在那里更改 CustomB 属性的值?我认为转换器用于将值从一种类型转换为另一种类型,例如将字符串转换为布尔值,而不是用于设置不同/多个属性的值
-
如果是这样的场景:当 CustomA 为真时,您希望 CustomB 为假,反之亦然。将它们绑定在一起,IValueConverter 就可以完成这项工作。
-
所以我将 MultiBinding 与转换器一起使用,但我是否需要使用 IMultiValueConverter,因为有两个值需要更改?我可以稍后再引入更多属性进行绑定吗?我的主要想法是改变一个属性的值,然后改变许多其他属性的值
标签: c# wpf vb.net xaml user-controls