How to enable users to edit a control style in run

2019-08-28 22:19发布

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:

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

1条回答
叛逆
2楼-- · 2019-08-28 22:57

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

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.

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();
}
查看更多
登录 后发表回答