我有一个wpf应用程序,我希望将单选按钮的颜色转换为(绿色/红色)与布尔值相比:
在Xaml文件中
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<local:BooleanToColorConverter x:Key="ToColorConverter"/>
</UserControl.Resources>
...........
<DataGridCheckBoxColumn Header="Statut" Binding="{Binding IsOnline, Mode=OneWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="True"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RadioButton Foreground="{Binding IsOnline, Mode=OneWay, UpdateSourceTrigger=LostFocus, Converter={StaticResource ToColorConverter}}" IsChecked="True" >
</RadioButton>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我添加了这个转换器:
public class BooleanToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool blnIsConnected = (bool)value;
return (blnIsConnected == true) ? Brushes.Green : Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (value == Brushes.Green) ? true : false;
}
}
我得到了结果:
我在所有情况下都得到了蓝色!!
修改
我尝试像这样编辑单选按钮模板
<DataGridCheckBoxColumn Header="Statut" Binding="{Binding IsOnline, Mode=OneWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="True"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RadioButton IsChecked="True" >
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<BulletDecorator Background="Transparent">
<BulletDecorator.Bullet>
<Grid Width="13" Height="13">
<Ellipse x:Name="CheckMark" Margin="4" Visibility="Collapsed">
<Ellipse.Fill>
<SolidColorBrush Color="{Binding IsOnline, UpdateSourceTrigger=LostFocus, Converter={StaticResource ToColorConverter}}" />
</Ellipse.Fill>
</Ellipse>
</Grid>
</BulletDecorator.Bullet>
</BulletDecorator>
</ControlTemplate>
</Setter.Value>
</Setter> </Style>
</RadioButton>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我得到了相同的结果
答案 0 :(得分:1)
1)您应为DataContext
项目的子项指定DataGridTemplateColumn
。默认情况下,它采用父上下文(例如,您的ViewModel)。解决方案:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid DataContext="{Binding}">
...
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
2)你只能用RadioButton绘制BulletDecorator
(最终解决方案是):
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<BulletDecorator DataContext="{Binding}">
<BulletDecorator.Bullet>
<Ellipse x:Name="CheckMark" Margin="4" Visibility="Visible"
Width="10" Height="10"
Fill="{Binding IsOnline, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ToColorConverter}}"></Ellipse>
</BulletDecorator.Bullet>
</BulletDecorator>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>