[英]How to easily allow users to update Styles used be elements in XAML (UWP)
這適用於 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),其中包含供用戶更新各種樣式設置的文本框。
但我不確定如何將這些綁定到 style.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}" />
有人可以指出我正確的方向嗎? 我正在嘗試以盡可能少的(或沒有背后的代碼)來做到這一點。
不幸的是,這種用戶定義的樣式在 UWP 中並不容易獲得。 但是,您可以使用數據綁定來實現一種樣式解決方案。
第一步是創建一個像CustomUISettings
這樣的類,它實現INotifyPropertyChanged
並具有HeaderFontSize
等屬性。
現在在應用程序啟動時創建此類的一個實例並將其添加為應用程序資源:
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
類中的所有屬性CustomUISettings
觸發PropertyChanged
事件。 例如,您可以在此處查看如何實現INotifyPropertyChanged
接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.