2011-03-08 23 views
0

可以使用什麼方法使用戶能夠通過在某些自定義控件樣式中設置個人值來定義他們自己的應用程序首選項?如何使用戶能夠在運行時編輯控件樣式?

我們可以在設計時將它們設置在XAML:

<UserControl.Resources> 
    <Style TargetType="{x:Type cc:MyControl}"> 
      <Setter Property="SWidth" Value="20" /> 
      ... 
      <Setter Property="SBrush" Value="Blue" />    
    </Style> 
</UserControl.Resources> 

但如何在運行時編輯這些樣式值?

回答

1

您會希望將樣式中的值綁定到某個靜態類(例如應用程序的默認設置),該類可以由任何類定義值來定義值。

在下面的應用程序中,我在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(); 
} 
相關問題