2015-07-20 43 views
2

我是WPF的新手。我的要求是以乾淨的方式實現樣式。造型包括字體,顏色,佈局,大小等。等與風格哪種方式應該定義資源字典以保持我的代碼清潔?

Style

樣品執行如上所示。要求在窗口中如果其接受用戶輸入的表單,常用樣式需要像標籤一樣右對齊,文本框必須左對齊並且有一些寬度以及一些屬性和前景屬性。

我實現

我做了一個單獨的組件(因爲不僅爲達到此目的,包括其他用戶控件,樣式,資源),其具有Layout.Xaml資源字典和它的所有樣式定義。

然後創建一個依賴項屬性,並通過該字典鏈接,如下所示。

<Window xmlns:MvvmLibsTests="clr-namespace:CreativeEye.TestConsole.MvvmLibsTests" 
     x:Class="CreativeEye.TestConsole.MvvmLibsTests.StyleTestView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="SyleTestView" Height="408" Width="706" 
     WindowStartupLocation="CenterScreen"   
     xmlns:Styles="clr-namespace:CreativeEye.MvvmLibs.Behaviours;assembly=CreativeEye.MvvmLibs"> 

<!--<Grid>--> 
<Grid Styles:SetLayout.Resources="{StaticResource FormLayoutStyle}"> 
</Grid> 
</Window> 

在這FormLayoutStyle具有值

<s:String x:Key="FormLayoutStyle">pack://application:,,,/CreativeEye.MvvmLibs;component/Resources/Layout.xaml</s:String> 
在應用程序的App.xaml中

的依賴項屬性的代碼是

public static readonly DependencyProperty ResourcesProperty = DependencyProperty.RegisterAttached(
      "Resources", 
      typeof(string), 
      typeof(SetLayout), 
      new PropertyMetadata("", new PropertyChangedCallback(CallBack))); 

    private static void CallBack(DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     var layoutGridStylePath = e.NewValue; 

     if (layoutGridStylePath == null) 
     { 
      return; 
     } 

     var uri = new Uri((string)layoutGridStylePath, UriKind.RelativeOrAbsolute); 
     var grid = obj as FrameworkElement; 

     if (grid == null) 
     { 
      return; 
     } 

     grid.Resources.Source = uri; 
    } 

和我取得的成果。

但我想知道這是一個好方法嗎?

而且我還讀了一些關於內存泄漏的內容。 參考鏈接link 1link 2

我比較困惑。我無法正確理解。

任何人都可以請在我的執行說這樣的內存泄漏問題將der?

+0

好主意,好工作 –

回答

1

通常我使用這種方式的資源,但綁定到C#代碼也不是一個壞的方法。

<Window x:Class="WPFDemo.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <Window.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary 
        Source="Resources/MyResourceDictionary.xaml"> 
       </ResourceDictionary> 
       <ResourceDictionary 
        Source="Resources/OthersStyle.xaml"> 
       </ResourceDictionary> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </Window.Resources> 
    <Grid> 
     <Image Source="/Images/logo.jpg"></Image> 
    </Grid> 
</Window>