您會希望將樣式中的值綁定到某個靜態類(例如應用程序的默認設置),該類可以由任何類定義值來定義值。
在下面的應用程序中,我在Settings.settings
文件中創建了一個名爲FontSize
的屬性。我添加了相應的命名空間中的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>
我直接綁定到的值一個TextBox
但不言而喻的是一些控制機制,例如一個視圖模型,強烈建議。
最後,如果你想保存設置,所有你需要做的就是調用類的Save
方法,例如,在應用程序的Exit
事件的事件處理程序:
private void Application_Exit(object sender, ExitEventArgs e)
{
WpfApplication1.Properties.Settings.Default.Save();
}