简体   繁体   English

如何使用户能够在运行时中编辑控件样式?

[英]How to enable users to edit a control style in runtime?

What approach can be used for enabling users to define their own application preferences by setting personal values in some custom controls styles? 通过使用某些自定义控件样式设置个人值,可以使用哪种方法使用户能够定义自己的应用程序首选项?

We can set them in XAML in design-time: 我们可以在设计时在XAML中设置它们:

<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. 您将需要将样式中的值绑定到某个静态类(例如,应用程序的默认设置),该类可以通过任何定义值的类进行修改。

In the app below, I created a property called FontSize in the Settings.settings file. 在下面的应用程序中,我在Settings.settings文件中创建了一个名为FontSize的属性。 I added the appropriate namespace in the XAML file and can now bind to it as I like: 我在XAML文件中添加了适当的名称空间,现在可以根据需要绑定到该名称空间:

<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>

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. 我将值直接绑定到TextBox但是不用说,强烈建议在视图模型中使用某些控制机制。

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: 最后,如果要保存设置,则只需在应用程序的Exit事件的事件处理程序中调用类的Save方法Exit

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM