这适用于Windows 10 UWP。我需要允许用户更新与整个应用程序中使用的元素相关联的样式的值(即允许用户更改各种文本块的字体大小,背景颜色堆栈面板等)。
我目前将所有样式都放在一个单独的文件中。
我的App.xaml
如下:
<Application
x:Class="MyTestApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Styles/Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
我的Styles.xaml
(部分)如下:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="using:MyTestApp.Views"
xmlns:x1="using:System">
<Style x:Key="HeaderTextBlocks" TargetType="TextBlock" BasedOn="{StaticResource TitleTextBlockStyle}">
<Setter Property="FontSize" Value="24"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="TextWrapping" Value="NoWrap"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Bottom"/>
<Setter Property="Margin" Value="10,4,0,0"/>
</Style>
<Style x:Key="RegularTextBlocks" TargetType="TextBlock" BasedOn="{StaticResource TitleTextBlockStyle}">
<Setter Property="FontSize" Value="12"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="TextWrapping" Value="NoWrap"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Bottom"/>
<Setter Property="Margin" Value="0,0,0,0"/>
</Style>
</ResourceDictionary>
我在整个应用程序中使用这样的控件来引用这些样式:
<TextBlock Style="{StaticResource HeaderTextBlocks}" />
我创建了一个设置页面(settings.xaml),其中包含用于更新各种样式设置的文本框。
但我不确定如何将这些绑定到styles.xaml文件上各种样式的设置,以便更新样式,并在用户更改值时更新引用样式的控件
<TextBox Header="Font Size of Header TextBlocks" Text="{x:Bind HeaderTextBlocks.FontSize ???, Mode=TwoWay}" />
<TextBox Header="Font Size of Regular TextBlocks" Text="{x:Bind RegularTextBlocks.FontSize???, Mode=TwoWay}" />
有人可以指出我正确的方向吗?我试图用尽可能少的(或没有代码)来做到这一点。
答案 0 :(得分:1)
不幸的是,UWP中不容易使用这种用户定义的样式。但是,您可以使用数据绑定实现一种样式解决方案。
第一步是创建一个类CustomUISettings
的类,它实现INotifyPropertyChanged
并具有HeaderFontSize
等属性。
现在在应用开始时创建此类的实例并将其添加为app资源:
Application.Current.Resources["CustomUISettings"] = new CustomUISettings();
现在,您可以在代码中的任何位置绑定到此类中的属性:
<TextBox FontSize="{Binding HeaderFontSize, Source={StaticResource CustomUISettings}}" />
您必须使用经典的{Binding}
标记扩展程序,因为{x:Bind}
不支持Source
设置。
要修改UI设置,您只需在任何地方检索实例,并根据需要设置属性:
var customUISettings = (CustomUISettings)Application.Current.Resources["CustomUISettings"];
customUISettings.HeaderFontSize = 50;
您必须确保CustomUISettings
类中的所有属性都会触发PropertyChanged
事件。您可以查看如何实现INotifyPropertyChanged
接口,例如here。