我尝试在必要时为字符串值定义常量,以避免在代码中隐藏“魔术字符串”。我最近发现自己需要为转换器定义自定义格式字符串,因此我public const string MyFormat = "a";在转换器中定义了。使用转换器时,我需要传入“a”作为ConverterParameter,但我不想输入 ,而是ConverterParameter=a引用命名常量。
<TextBlock Text="{x:Bind SomeProperty, Converter={StaticResource MyConverter}, ConverterParameter=???}" />
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了ConverterParameter=local:MyConverter.MyFormat,但它只是传递字符串“local:MyConverter.MyFormat”而不是“a”。
我已经尝试过ConverterParameter={x:Bind local:MyConverter.MyFormat},但出现错误Nested x:Bind expressions are not supported.
我尝试过ConverterParameter={StaticResource MyFormat}将其添加为资源,但这只是转移了问题并引入了一个新问题:
<x:String x:Key="MyFormat">a</x:String>,但是我已经在两个不同的地方定义了常量,如果它发生变化,我必须记住在两个不同的地方更新它。有没有办法在 XAML 中引用命名常量?(注意:这是 UWP,而不是 WPF。)
这是一个简单的重现:
主页.xaml
<Page
x:Class="XamlConstantReference.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:local="using:XamlConstantReference"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Page.Resources>
<local:MyConverter x:Key="MyConverter" />
<!-- How do I refer to MyConverter.MyFormat rather than defining it a second time? -->
<x:String …Run Code Online (Sandbox Code Playgroud)