Sta*_*ker 6 wpf resources xaml user-controls overriding
我有以下内容UserControl:
<UserControl x:Class="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<SolidColorBrush x:Key="ColorKey" Color="Orange"/>
</UserControl.Resources>
<Grid Background="{StaticResource ColorKey}">
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:OverrideResource"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="OtherColorKey" Color="Blue"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<local:MyControl Grid.Row="0">
<local:MyControl.Resources>
<SolidColorBrush x:Key="ColorKey" Color="Red"/>
</local:MyControl.Resources>
</local:MyControl>
<Grid Grid.Row="1">
<Grid.Resources>
<SolidColorBrush x:Key="OtherColorKey" Color="Green"/>
</Grid.Resources>
<Grid Background="{StaticResource OtherColorKey}"/>
</Grid>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
覆盖资源OtherColorKey就像我期望的那样; 网格有绿色Background.但我想覆盖(在我的例子中)Resource内部使用的.但我得到例外:UserControlColorKey
项目已添加.键入字典:添加'ColorKey'键:'ColorKey'
这只是一个简化的例子,实际上我需要它来完成更复杂的任务.我知道,对于例如,DevExpress使用类似的机制来自定义它们的控件(但是它们不使用字符串作为键,而是使用派生的对象ResourceKey).但是我无法找到简单的工作示例来自己实现这样的事情.
谢谢你的帮助.
OtherColorKey 被添加到 2 个不同的字典(窗口和网格)中。ColorKey 被添加到同一字典 (MyControl) 中。
解决此问题的更好方法是在 MyControl 中声明 Brush 类型的 DependencyProperty 并将其设置为:
<local:MyControl Grid.Row="0" MyBrush="Red" />
Run Code Online (Sandbox Code Playgroud)
在 MyControl 中,只需将您想要的任何内容绑定到 MyBrush 属性即可。
<UserControl x:Class="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name=Me>
<Grid Background="{Binding MyBrush, ElementName=Me}">
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5709 次 |
| 最近记录: |