在WPF中绑定来自xaml的代码中的const成员

Aki*_*24x 9 c# wpf bind uid

有没有什么好的方法可以将属性绑定到代码隐藏中的const值?

当我使用ComboBox时,我通常在xaml和代码后面这样做:

XAML:

<ComboBox Name="cbBuz">
   <ComboBoxItem Content="foo" Uid="foo" IsSelected="true" />
   <ComboBoxItem Content="bar" Uid="bar" />
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

ComboBoxItem item = cbBuz.GetSelectedItem();
switch (item.Uid)
{
    case "foo":  ... break;
    case "bar":  ... break;
}
Run Code Online (Sandbox Code Playgroud)

我选择这种方式的原因如下:

  • 出于本地化目的,不应使用内容字符串来确定在保存和加载上一个选定项目期间选择了哪个项目.
  • 为简单起见,XAML和代码隐藏应该连接内部标识符(在本例中为Uid).因此,XAML和Code-behind可以单独维护.

但是,在维护方面,内部标识符应该在一个地方定义,如下所示:

//IDs
public const string ID_foo = "foo";
public const string ID_bar = "bar";

...

//
switch (item.Uid)
{
    case ID_foo:  ... break;
    case ID_bar:  ... break;
}
Run Code Online (Sandbox Code Playgroud)

问题是看似属性不能是const值,所以没有办法将ID_foo和ID_bar绑定到ComboBoxItem的Uid,如下所示:

//If ID_foo and ID_bar are properties, this will work.
<ComboBox Name="cbBuz">
   <ComboBoxItem Content="foo" Uid="{Binding ID_foo}" IsSelected="true" />
   <ComboBoxItem Content="bar" Uid="{Binding ID_bar}" />
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

所以,我想知道如何解决这个问题.或者,有没有更好的方法来实现它.这也很好.

最好,

Cod*_*ked 24

最好使用StaticExtension,如下所示:

Uid="{x:Static local:YourClass.ID_foo}"
Run Code Online (Sandbox Code Playgroud)

其中local是您的类的C#名称空间的xmlns别名.更多信息可以在这里找到.

使用Binding的问题是你为永远不会改变的东西增加了很多开销.绑定将尝试监控您的财产.此外,在未实现INotifyPropertyChanged的对象上使用具有非依赖属性的Binding 已知存在"泄漏".

  • 专业提示:当常量是数字时,请确保类型匹配。我尝试使用 int 并尝试在 XAML 中设置 System.Windows.FrameworkElement.Height(双精度值),它给了我一个 XamlParseException:“'23' 不是属性 'Height' 的有效值。” (2认同)