如何使用户能够在运行时中编辑控件样式? [英] How to enable users to edit a control style in runtime?

查看:68
本文介绍了如何使用户能够在运行时中编辑控件样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用哪种方法通过在某些自定义控件样式中设置个人值来使用户定义自己的应用程序首选项?

What approach can be used for enabling users to define their own application preferences by setting personal values in some custom controls styles?

我们可以在设计中的XAML中设置它们时间:

We can set them in XAML in design-time:

<UserControl.Resources>
    <Style TargetType="{x:Type cc:MyControl}">
            <Setter Property="SWidth" Value="20" />
            ...
            <Setter Property="SBrush" Value="Blue" />              
    </Style>
</UserControl.Resources>

但是如何在运行时编辑这些样式值?

But how to edit these style values in runtime?

推荐答案

您将需要将样式中的值绑定到某个静态类(例如,应用程序的默认设置),该类可以通过定义该值的类进行修改。

You'll want to bind the values in your style to some static class—for example, the application's default settings—that can be modified by whatever class defines what the values should be.

在下面的应用程序中,我在设置中创建了一个名为 FontSize 的属性。 .settings 文件。我在XAML文件中添加了适当的名称空间,现在可以根据需要绑定到该名称空间:

In the app below, I created a property called FontSize in the Settings.settings file. I added the appropriate namespace in the XAML file and can now bind to it as I like:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication1"
        xmlns:prop="clr-namespace:WpfApplication1.Properties"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition />
        </Grid.RowDefinitions>

        <Grid.Resources>
            <Style TargetType="TextBlock" x:Key="myStyle">
                <Setter Property="FontSize" Value="{Binding FontSize, Source={x:Static prop:Settings.Default}}" />
            </Style>
        </Grid.Resources>

        <TextBlock Style="{DynamicResource myStyle}" Text="The quick brown fox jumped over the lazy dog." />

        <TextBox Grid.Row="1" Text="{Binding FontSize, Source={x:Static prop:Settings.Default}, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</Window>

我直接将值绑定到 TextBox 但是不用说,强烈建议在视图模型中使用某种控制机制。

I bound the value directly to a TextBox but it goes without saying that some control mechanism, in a viewmodel for instance, is strongly recommended.

最后,如果要保存设置,您要做的所有事情例如,在应用程序的 Exit 事件的事件处理程序中,调用类的 Save 方法:

Finally, if you want to save the settings, all you have to do is call the class's Save method, for example, in the event handler of the application's Exit event:

private void Application_Exit(object sender, ExitEventArgs e)
{
    WpfApplication1.Properties.Settings.Default.Save();
}

这篇关于如何使用户能够在运行时中编辑控件样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆