如何在 C# 中定义常量并在 XAML 中使用它?

Jer*_*ier 5 c# data-binding converters uwp uwp-xaml

我尝试在必要时为字符串值定义常量,以避免在代码中隐藏“魔术字符串”。我最近发现自己需要为转换器定义自定义格式字符串,因此我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}将其添加为资源,但这只是转移了问题并引入了一个新问题:

  1. 我也不知道如何引用资源中的常量。我可以添加<x:String x:Key="MyFormat">a</x:String>,但是我已经在两个不同的地方定义了常量,如果它发生变化,我必须记住在两个不同的地方更新它。
  2. 即使我这样做,字符串也不会按预期作为参数传递。参数为空。

有没有办法在 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 x:Key="MyFormat">a</x:String>
    </Page.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <!--  How do I refer to MyConverter.MyFormat rather than passing in ConverterParameter=a?  -->
        <TextBlock Grid.Row="0" Text="{x:Bind SomeProperty, Converter={StaticResource MyConverter}, ConverterParameter=a}" />
        <TextBlock Grid.Row="1" Text="{x:Bind SomeProperty, Converter={StaticResource MyConverter}, ConverterParameter=local:MyConverter.MyFormat}" />
        <!-- <TextBlock Grid.Row="2" Text="{x:Bind SomeProperty, Converter={StaticResource MyConverter}, ConverterParameter={x:Bind local:MyConverter.MyFormat}}" /> -->
        <TextBlock Grid.Row="3" Text="{x:Bind SomeProperty, Converter={StaticResource MyConverter}, ConverterParameter={StaticResource MyFormat}}" />
    </Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)

MainPage.xaml.cs

using System.ComponentModel;
using Windows.UI.Xaml.Controls;

namespace XamlConstantReference
{
    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _someProperty = "Hello World!";

        public string SomeProperty
        {
            get => _someProperty;
            set
            {
                if (_someProperty != value)
                {
                    _someProperty = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SomeProperty)));
                }
            }
        }

        public MainPage()
        {
            InitializeComponent();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的转换器.cs

using System;
using Windows.UI.Xaml.Data;

namespace XamlConstantReference
{
    public class MyConverter : IValueConverter
    {
        public const string MyFormat = "a";

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (parameter == null)
            {
                return $"Fail. Formatted '{value}' with null parameter.";
            }
            else if (parameter is string parameterString)
            {
                switch (parameterString)
                {
                    case MyFormat:
                        return $"Success! Formatted '{value}' with parameter '{parameterString}'.";

                    default:
                        return $"Fail. Formatted '{value}' with parameter '{parameterString}'.";
                }
            }

            throw new ArgumentException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)