小编Jer*_*ier的帖子

如何在 C# 中定义常量并在 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 …
Run Code Online (Sandbox Code Playgroud)

c# data-binding converters uwp uwp-xaml

5
推荐指数
0
解决办法
2114
查看次数

标签 统计

c# ×1

converters ×1

data-binding ×1

uwp ×1

uwp-xaml ×1