我正在嘗試實作一個值轉換器,它將根據用戶控制元件“MyUserControl”的自定義“MyUserControlStatus”屬性更改用戶控制元件上按鈕的顏色。
代碼隱藏如下所示:
Public Class MyUserControl
Public Property MyUserControlStatus As Integer = 0
End Class
Public Class StatusIndicatorConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
Dim indicatorbrush As Brush = Brushes.Transparent
Dim status As Integer = CType(value, Integer)
Select Case status
Case 0 : indicatorbrush = Brushes.Red
Case 1: indicatorbrush = Brushes.Green
Case 2 : indicatorbrush = Brushes.Yellow
End Select
Return indicatorbrush
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class
XAML 如下所示:
<UserControl x:Class="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"
xmlns:local="clr-namespace:MainApplicationName"
xmlns:wpf="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF"
mc:Ignorable="d"
>
<UserControl.Resources>
<local:StatusIndicatorConverter x:Key="MyStatusIndicatorConverter"/>
</UserControl.Resources>
<Button x:Name="ButtonStatusIndicator"
Background="{Binding Path=MyUserControlStatus, Converter={StaticResource MyStatusIndicatorConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
>
<Button.Resources>
<Style TargetType="Border">
<Setter Property="Height" Value="10"/>
<Setter Property="Width" Value="10"/>
<Setter Property="CornerRadius" Value="10"/>
</Style>
</Button.Resources>
</Button>
</UserControl>
我得到一個空的、非彩色的狀態。Convert 函式中的斷點不會觸發。我不確定我在這里做錯了什么,因為所有部分似乎都已到位。它應該使按鈕指示器變為紅色(對于值 = 0)。期望是,隨著 MyUserControlStatus 的變化,指示器按鈕的顏色也會發生變化,因為它系結到 MyUserControlStatus 并且該值被轉換為顏色。
uj5u.com熱心網友回復:
UserControl 的 XAML 中與其自身屬性之一的系結必須顯式設定系結的源物件,例如通過設定 RelativeSource 屬性。
Mode=TwoWay然而,設定UpdateSourceTrigger=PropertyChanged并沒有意義。它在這個 Binding 中根本沒有任何作用。
Background="{Binding Path=MyUserControlStatus,
RelativeSource={RelativeSource AncestorType=UserControl},
Converter={StaticResource MyStatusIndicatorConverter}}"
除此之外,源屬性必須觸發更改通知才能更新系結目標屬性。
它應該被實作為依賴屬性:
Public Shared ReadOnly MyUserControlStatusProperty As DependencyProperty =
DependencyProperty.Register(
name:="MyUserControlStatus",
propertyType:=GetType(Integer),
ownerType:=GetType(MyUserControl))
Public Property MyUserControlStatus As Integer
Get
Return CType(GetValue(MyUserControlStatusProperty), Integer)
End Get
Set
SetValue(MyUserControlStatusProperty, Value)
End Set
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494720.html
