我目前正在开发一个WPF应用程序,并重新定义了按钮和复选框,以便在App.xaml中使用自定义样式。
的App.xaml
<Style x:Key="{x:Type CheckBox}" TargetType="CheckBox">
<Setter Property="Margin" Value="0,0,10,5" />
<Setter Property="Width" Value="85" />
<Setter Property="Height" Value="50" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="FocusVisualStyle"
Value="{DynamicResource CheckBoxFocusVisual}" />
<Setter Property="Template" />
<Setter.Value />
<!-- ... etc. -->
</Style>
代码来自here并进行了一些修改。
现在我想通过编码来改变背景颜色。例如,如果复选框的标题是“a”,则背景颜色将为红色,依此类推。我成功地绑定了标题而不是背景颜色。我的复选框用在控件项目中。
MainWindow.xaml
<Grid>
<ItemsControl Name="ControllerDisplay">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding controltitle}"
Style="{StaticResource MainControltitle}"/>
<CheckBox>
// want to change checkbox background
<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}"
BasedOn="{StaticResource {x:Type CheckBox}}">
<Setter Property="Background" Value="Aqua" />
</Style>
</CheckBox.Style>
<StackPanel >
<TextBlock Text="{Binding controlno}" HorizontalAlignment="Center"
FontSize="16" />
<TextBlock Text="{Binding status}" HorizontalAlignment="Center"
FontSize="10"/>
</StackPanel>
</CheckBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
编码方:
public void printcheckbox()
{
List<Controller> listItem = new List<Controller>();
listItem.Add(new Controller() { controltitle = "title1", controlno = "12345",
status = "On" , controlbg = Colors.Red});
ControllerDisplay.ItemsSource = listItem;
}
public class Controller
{
public string controltitle { get; set; }
public string controlno { get; set; }
public string status { get; set; }
public Color controlbg { get; set; }
}