C# 如何将ResourceDictionary样式应用于代码隐藏文件中的控件
我在自己的文件中有一个ResourceDictionary,定义如下:C# 如何将ResourceDictionary样式应用于代码隐藏文件中的控件,c#,wpf,visual-studio-2010,resourcedictionary,C#,Wpf,Visual Studio 2010,Resourcedictionary,我在自己的文件中有一个ResourceDictionary,定义如下: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loca
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WordSearch">
<Style x:Key="labelStyle">
<Setter Property="Label.Foreground" Value="#8860D0"/>
</Style>
</ResourceDictionary>
在我的代码隐藏文件中,我有一个包含一些标签控件的标签列表
private List<Label> labels;
私有列表标签;
是否有任何方法可以将ResourceDisctionary中的样式应用于我的所有标签?到目前为止,我已经做到了这一点,但风格没有得到应用:
ResourceDictionary skin = Application.LoadComponent(new Uri("BrightTheme.xaml", UriKind.Relative)) as ResourceDictionary;
Resources.MergedDictionaries.Add(skin);
for (int i = 0; i < labels.Count; i++)
{
labels[i].Style = (Style)skin["labelStyle"];
}
ResourceDictionary skin=Application.LoadComponent(新Uri(“BrightTheme.xaml”,UriKind.Relative))作为ResourceDictionary;
Resources.MergedDictionaries.Add(皮肤);
对于(int i=0;i
正如我在回答之前的评论中所述,如果最终目标是主题化,那么标签是由程序自动生成还是用xaml硬编码并不重要。您希望采取的方法是交换ResourceDictionary主题,看起来您正在尝试这样做,尽管我看到您只是添加而不是删除
此外,不需要将每个标签的样式设置为键。因为应用标签的整体样式取决于ResourceDictionary
下面是一个例子:
Dictionary1.xaml:这是一个主题。请注意,第二种样式是将labelStyle应用于所有标签的样式
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="labelStyle" TargetType="Label">
<Setter Property="Foreground" Value="#8860D0"/>
</Style>
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource labelStyle}"/>
</ResourceDictionary>
private bool useSecondTheme;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
useSecondTheme = !useSecondTheme;
userControl1.SwapTheme(useSecondTheme);
}
UserControl1.xaml
<Grid>
<StackPanel>
<Button Content="Swap Theme" Click="Button_Click" Margin="15"/>
<local:UserControl1 x:Name="userControl1" Margin="5"/>
</StackPanel>
</Grid
<Grid>
<StackPanel>
<ListBox ItemsSource="{Binding MyLabels}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border>
<Label Margin="5" Content="{Binding}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<Button Click="Button_Click" Content="Add Random Label" Margin="5"/>
</StackPanel>
</Grid>
UserControl1.xaml.cs:特别关注交换方式
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ApplyLabelStyleOnUserControl">
<Style x:Key="labelStyle" TargetType="Label">
<Setter Property="Foreground" Value="DarkGreen"/>
</Style>
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource labelStyle}"/>
</ResourceDictionary>
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace ApplyLabelStyleOnUserControl
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
private ObservableCollection<string> myLabels;
public ObservableCollection<string> MyLabels
{
get
{
if (this.myLabels == null)
this.myLabels = new ObservableCollection<string>();
return this.myLabels;
}
}
private static Random random = new Random();
public string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public UserControl1()
{
InitializeComponent();
this.DataContext = this;
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
// Initialize it with 5 random strings, but allow more labels to be added with a button on the UI.
MyLabels.Add(RandomString(25));
MyLabels.Add(RandomString(25));
MyLabels.Add(RandomString(25));
MyLabels.Add(RandomString(25));
MyLabels.Add(RandomString(25));
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Swaps between two themes
/// </summary>
/// <param name="useSecondTheme">when true it uses Dictionary2.xaml resource dictionary, otherwise it uses Dictionary1.xaml</param>
internal void SwapTheme(bool useSecondTheme)
{
if (useSecondTheme)
{
// Remove the old theme
ResourceDictionary oldSkin = Application.LoadComponent(new Uri("Dictionary1.xaml", UriKind.Relative)) as ResourceDictionary;
Resources.MergedDictionaries.Remove(oldSkin);
// Add the new theme
ResourceDictionary newSkin = Application.LoadComponent(new Uri("Dictionary2.xaml", UriKind.Relative)) as ResourceDictionary;
Resources.MergedDictionaries.Add(newSkin);
}
else
{
// Remove the old theme
ResourceDictionary oldSkin = Application.LoadComponent(new Uri("Dictionary2.xaml", UriKind.Relative)) as ResourceDictionary;
Resources.MergedDictionaries.Remove(oldSkin);
// Add the new theme
ResourceDictionary newSkin = Application.LoadComponent(new Uri("Dictionary1.xaml", UriKind.Relative)) as ResourceDictionary;
Resources.MergedDictionaries.Add(newSkin);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyLabels.Add(RandomString(25));
}
}
}
使用系统;
使用System.Collections.ObjectModel;
使用系统组件模型;
使用System.Linq;
使用System.Windows;
使用System.Windows.Controls;
命名空间ApplyLabelStyleOnUserControl
{
///
///UserControl1.xaml的交互逻辑
///
公共部分类UserControl1:UserControl,INotifyPropertyChanged
{
私人可观察收集MyLabel;
公共可观测集合MyLabels
{
得到
{
if(this.myLabels==null)
this.myLabels=新的ObservableCollection();
返回此.myLabels;
}
}
私有静态随机=新随机();
公共字符串随机字符串(整数长度)
{
常量字符串chars=“abcdefghijklmnopqrstuvwxyz012456789”;
返回新字符串(可枚举。重复(字符,长度)
.Select(s=>s[random.Next(s.Length)]).ToArray();
}
公共用户控制1()
{
初始化组件();
this.DataContext=this;
此.Loaded+=已加载;
}
已加载专用void(对象发送方,RoutedEventArgs e)
{
//使用5个随机字符串初始化它,但允许通过UI上的按钮添加更多标签。
添加(随机字符串(25));
添加(随机字符串(25));
添加(随机字符串(25));
添加(随机字符串(25));
添加(随机字符串(25));
}
公共事件属性更改事件处理程序属性更改;
///
///两个主题之间的交换
///
///如果为true,则使用Dictionary2.xaml资源字典,否则使用Dictionary1.xaml
内部虚空交换(布尔使用第二主题)
{
如果(使用第二个主题)
{
//删除旧主题
ResourceDictionary oldSkin=Application.LoadComponent(新Uri(“Dictionary1.xaml”,UriKind.Relative))作为ResourceDictionary;
Resources.MergedDictionaries.Remove(oldSkin);
//添加新主题
ResourceDictionary newSkin=Application.LoadComponent(新Uri(“Dictionary2.xaml”,UriKind.Relative))作为ResourceDictionary;
Resources.MergedDictionaries.Add(newSkin);
}
其他的
{
//删除旧主题
ResourceDictionary oldSkin=Application.LoadComponent(新Uri(“Dictionary2.xaml”,UriKind.Relative))作为ResourceDictionary;
Resources.MergedDictionaries.Remove(oldSkin);
//添加新主题
ResourceDictionary newSkin=Application.LoadComponent(新Uri(“Dictionary1.xaml”,UriKind.Relative))作为ResourceDictionary;
Resources.MergedDictionaries.Add(newSkin);
}
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
添加(随机字符串(25));
}
}
}
每当我单击“交换主题”按钮时,它都会在我定义的两个ResourceDictionary之间切换:
尝试创建一个实际的
资源字典
,并设置其源
,而不是调用应用程序。LoadComponent
:
ResourceDictionary skin = new ResourceDictionary()
{
Source = new Uri("BrightTheme.xaml", UriKind.Relative)
};
for (int i = 0; i < labels.Count; i++)
{
labels[i].Style = (Style) skin["labelStyle"];
}
ResourceDictionary皮肤=新建ResourceDictionary()
{
Source=新Uri(“BrightTheme.xaml”,UriKind.Relative)
};
对于(int i=0;i
您需要在代码隐藏中执行吗?因为在UserControl的XAML中可以更轻松地实现这一点。我之所以想在代码隐藏中实现这一点,是因为该程序让用户有机会选择应用程序的不同主题。一旦选择了一个主题,我希望能够重新给这些标签上色。我还应该提到,这些标签是由程序自动生成的,不能硬编码为数量