在WPF中应用数据库字段的样式

3

我的问题是,我有不同的样式存储在数据库表中。我将获取这些样式并将其存储到某个字符串变量中。现在我想将这些样式应用到我的WPF控件上。那么我该怎么做呢?

例如:

我的代码是...

Window1.xaml
===========================

<Window x:Class="DynamicBindResourceDictionary.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Button Margin="103,64,68,86" Name="button1" Content="Click Here!" Style="{DynamicResource baseStyle}"></Button>
    </Grid>
</Window>

Window1.xaml.cs
================

public partial class Window1 : Window
{ 
    //Store the style here from database
    string style = "<Style x:Key='baseStyle' TargetType='{x:Type Button}'>" +
    "<Setter Property='FontSize' Value='15' />" +
    "<Setter Property='Background' Value='Red' /></Style>";

    public Window1()
    {
        InitializeComponent();
    /* How to do that?  */
    }
}

如果我们不能使用字符串变量,那么还有什么替代方案呢?

请帮助我。

Dharmesh

1个回答

1

试试这个:

    public MainWindow()
    {
        string styleString = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" x:Key='baseStyle' TargetType='{x:Type Button}' >" +
                             "<Setter Property='FontSize' Value='15' />" +
                             "<Setter Property='Background' Value='Red' />"+
                             "<Setter Property='Height' Value='18' />" +
                             "</Style>";
        StringReader stringReader = new StringReader(styleString);
        XmlReader xmlReader = XmlReader.Create(stringReader);
        Style readerLoadStyle = (Style)XamlReader.Load(xmlReader);            
        ResourceDictionary rd = new ResourceDictionary();
        rd.Add("baseStyle", readerLoadStyle);
        Application.Current.Resources.MergedDictionaries.Add(rd);
        InitializeComponent();            
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接