C# 如何在通用Windows应用程序中绑定到模板内的空值?
回答之前,请先查看。 首先得到答案可能会解决以下问题C# 如何在通用Windows应用程序中绑定到模板内的空值?,c#,xaml,win-universal-app,uwp,C#,Xaml,Win Universal App,Uwp,回答之前,请先查看。 首先得到答案可能会解决以下问题 这是一个刚从Windows 10(通用应用程序)开始出现的问题。在Windows8.1和其他每一种XAML技术中,这种技术都能完美地工作。以下是空白通用应用程序项目中的设置: 1。带有附加属性的静态类 创建包含类型为Brush的附加属性的类。把这个放在项目的任何地方 public static class MySettings { public static Brush GetAccentBrush(DependencyObject
这是一个刚从Windows 10(通用应用程序)开始出现的问题。在Windows8.1和其他每一种XAML技术中,这种技术都能完美地工作。以下是空白通用应用程序项目中的设置: 1。带有附加属性的静态类 创建包含类型为
Brush
的附加属性的类。把这个放在项目的任何地方
public static class MySettings
{
public static Brush GetAccentBrush(DependencyObject d)
{
return (Brush)d.GetValue(AccentBrushProperty);
}
public static void SetAccentBrush(DependencyObject d, Brush value)
{
d.SetValue(AccentBrushProperty, value);
}
public static readonly DependencyProperty AccentBrushProperty = DependencyProperty.RegisterAttached(
"AccentBrush",
typeof(Brush),
typeof(MySettings),
null
);
}
2。使用附加属性将控件添加到MainPage.xaml中
在主页中,添加一个带有自定义模板的ContentControl
,该模板具有一个Grid
,其背景颜色设置为强调笔刷。在样式中设置强调笔刷
<Page x:Class="UniversalTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="using:UniversalTest"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="MyControl"
TargetType="ContentControl">
<Setter Property="local:MySettings.AccentBrush"
Value="Green" /> <!-- Setting value here -->
</Style>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ContentControl Style="{StaticResource MyControl}">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Grid Background="{TemplateBinding local:MySettings.AccentBrush}"> <!-- Using value here -->
<TextBlock Text="Howdy World!" />
</Grid>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
</Grid>
</Page>
有人想试试这个吗?您可以添加一个假附加属性:
public static Brush GetNullAccentBrush(DependencyObject d)
{
return (Brush)d.GetValue(NullAccentBrushProperty);
}
public static void SetNullAccentBrush(DependencyObject d, Brush value)
{
d.SetValue(NullAccentBrushProperty, value);
}
public static readonly DependencyProperty NullAccentBrushProperty = DependencyProperty.RegisterAttached(
"NullAccentBrush",
typeof(SolidColorBrush),
typeof(MySettings),
null
);
并绑定属性设置程序:
<Setter Property="local:MySettings.AccentBrush"
Value="{Binding local:MySettings.NullAccentBrush}" />
网格背景为空(即使NullAccentBrush上没有实际绑定…。对于记录,此问题似乎已修复。我的项目引用了通用Windows版本10.0.10240.0。将画笔设置为{x:Null}正如原始海报所描述的那样,效果与预期一样。我在资源文件中发现此代码可以工作
<Color x:Key="BgNull"></Color>
然后以您的风格使用指向BgNull的链接
<Setter Property="Background" Value="{StaticResource BgNull}"/>
试试刷子怎么样?
而不是刷子刷子是一个类Nullable
仅适用于结构。为什么要将该值设置为null?上面的示例是一个更大问题的一部分。我们尽可能地重复使用样式,以获得更干净的外观和感觉。某些样式可能将此值设置为真实画笔,而继承者可以使用{x:Null}
禁用它。顺便说一句,此
在运行时工作,但设计师会抱怨。
<Setter Property="Background" Value="{StaticResource BgNull}"/>