我知道如何在xaml中设置TabPanel的背景颜色,如下所示:
<TabControl.Resources>
<Style x:Key="noClue" TargetType="{x:Type TabPanel}">
<Setter Property="Background" Value="Transparent"></Setter>
</Style>
</TabControl.Resources>
但是,当我单击WPF应用程序上的按钮时,我想更改此背景颜色,这意味着在运行时更改它。有没有办法做到这一点?
提前感谢您的时间。
答案 0 :(得分:1)
是的,您可以将TabPanel的Background属性绑定到View / ViewModel中的属性,并在单击按钮时更改它。绑定的XAML看起来像是这样的:
<TabPanel Background="{Binding Path=BackgroundColor}"/>
您的媒体资源名称为BackgroundColor。后台是Brush,因此在管理绑定时会考虑到这一点。您也可以从样式中获得绑定,但您可能需要RelativeSource
在样式中,试试这个
<Setter Property="Background" Value="{Binding BackgroundColor}" />
如果您的窗口绑定到DataContext。还可以尝试从你的风格中删除x:Key。这不是必需的。
编辑:这有效
风格
<Window.Resources>
<Style TargetType="{x:Type TabPanel}">
<Setter Property="Background" Value="{Binding BackgroundColor}"/>
</Style>
</Window.Resources>
窗口
public partial class MainWindow : Window, INotifyPropertyChanged
{
private SolidColorBrush backgroundColor = new SolidColorBrush(Colors.Black);
public SolidColorBrush BackgroundColor
{
get { return backgroundColor; }
set
{
if (backgroundColor == value)
return;
backgroundColor = value;
RaisePropertyChanged(nameof(backgroundColor));
}
}
public MainWindow()
{
InitializeComponent();
// Make sure to set the DataContext to this!
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
private void Button_Click(object sender, RoutedEventArgs e)
{
// Change the color through the property
if (BackgroundColor.Color == Colors.Black)
BackgroundColor = new SolidColorBrush(Colors.Transparent);
else
BackgroundColor = new SolidColorBrush(Colors.Black);
}
}
这绑定到View,您可能希望将其抽象为ViewModel并绑定到该ViewModel。此外,如果您确实将此颜色逻辑移动到ViewModel,您还可能希望将BackgroundColor属性中的SolidColorBrush
更改为Color或其他一些与UI无关的类型,但这取决于您。查看this和其他WPF MVVM相关文章,了解有关MVVM和绑定到ViewModels的更多信息