我是 WPF 新手。我的要求是以干净的方式实现样式。样式包括字体、颜色、布局、大小。等等
带有样式的示例实现如上所示。要求在一个窗口中,如果它是一个接收用户输入的表单,那么通用样式需要像标签必须右对齐,文本框必须左对齐以及一些宽度和一些属性以及前景属性。
我的实现
我制作了一个单独的程序集(因为不仅为了这个目的,它还包括其他用户控件、样式、资源),它有一个 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 具有值(value)
<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;
}
我取得了结果。
But i wanted to know is it a good way ?
我还阅读了一些有关内存泄漏的内容。 引用链接link 1 , link 2 .
我更糊涂了。我无法正确理解。
Can anyone please say in my implementation such memory leak problem will be der ?
最佳答案
我通常以这种方式使用资源,但绑定(bind)到 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>
关于c# - 我应该以哪种方式定义资源字典以保持我的代码干净?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31512930/