我有一个用户控件,它是一个椭圆形,类似于“ led”。我想将其“填充”绑定到布尔属性(状态)。 我为此使用了一个布尔到颜色转换器。
这是我所做的用户控件:
<UserControl x:Class="Sol.Components.Led"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
xmlns:conv="clr-namespace:Sol.Converters"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Ellipse Fill="{Binding Converter={StaticResource BoolToColor}}" StrokeThickness="3" Stroke="Gray"/>
</Grid>
</UserControl>
在用户控件中也无法识别转换器!我是这样做的
public class BoolToColor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
if ((bool)value == true)
return Colors.Green; // to replace with onColor
else
return Colors.Red; // to replace with offColor
}
return Colors.LightGray;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Color)
{
if ((Color)value == Colors.Green) // to compare with onColor
{
return true;
}
}
return false;
}
}
我使用了一个包含4个用户控制的窗口:
<Window x:Class="Sol.Menu.Leds"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:led="clr-namespace:Sol.Components"
xmlns:conv="clr-namespace:Sol.Converters"
Title="Leds" Height="300" Width="300">
<Window.Resources>
<conv:BoolToColor x:Key="BoolToColor" />
</Window.Resources>
<Grid>
...
<led:Led Grid.Column="0" Grid.Row="0" x:Name="led1" State="False"/>
<led:Led Grid.Column="0" Grid.Row="1" x:Name="led2" State="False"/>
<led:Led Grid.Column="1" Grid.Row="0" x:Name="led3" State="False"/>
<led:Led Grid.Column="1" Grid.Row="1" x:Name="led4" State="False"/>
</Grid>
</Window>
和使用的控件类:
public partial class Led : UserControl
{
private bool state;
public bool State
{
get { return state; }
set { state = value; }
}
private Color onColor;
public Color OnColor
{
get { return onColor; }
set { onColor = value; }
}
private Color offColor;
public Color OffColor
{
get { return offColor; }
set { offColor = value; }
}
public Led()
{
InitializeComponent();
}
}
这是没有绑定的作品,并且窗口显示了4个椭圆,但是我无法动态更改颜色(根据隐藏的代码)。 对解决绑定有帮助吗?
答案 0 :(得分:1)
您需要实现PropertyChanged,以便UI知道属性已更改。
答案 1 :(得分:1)
尝试绑定到State
的{{1}}属性:
UserControl
您还应该从转换器返回<Ellipse Fill="{Binding Path=State,
RelativeSource={RelativeSource AncestorType=UserControl},
Converter={StaticResource BoolToColor}}" StrokeThickness="3" Stroke="Gray"/>
而不是Brush
:
Color
答案 2 :(得分:0)
Fill与所有其他UI“颜色”属性一样,实际上是Brush
值,而不是Color
更改转换器以返回Brushes.Red / Brushes.Green。