gpt4 book ai didi

c# - 在 WPF 中的 xaml 代码中绑定(bind) const 成员

转载 作者:太空狗 更新时间:2023-10-29 17:31:24 24 4
gpt4 key购买 nike

有什么好的方法可以在代码隐藏中将属性绑定(bind)到 const 值吗?

当我使用 ComboBox 时,我通常在 xaml 和代码隐藏中这样做:

XAML:

<ComboBox Name="cbBuz">
<ComboBoxItem Content="foo" Uid="foo" IsSelected="true" />
<ComboBoxItem Content="bar" Uid="bar" />
</ComboBox>

代码隐藏:

ComboBoxItem item = cbBuz.GetSelectedItem();
switch (item.Uid)
{
case "foo": ... break;
case "bar": ... break;
}

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

  • 出于本地化目的,不应使用内容字符串来确定在保存和加载最后选择的项目期间选择了哪个项目。
  • 为简单起见,XAML 和代码隐藏应该连接内部标识符(在本例中为 Uid)。这样,XAML 和代码隐藏可以分开维护。

然而,在维护方面,内部标识符应该像这样在一个地方定义:

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

...

//
switch (item.Uid)
{
case ID_foo: ... break;
case ID_bar: ... break;
}

问题似乎是属性不能是常量值,所以没有办法像这样将 ID_foo 和 ID_bar 绑定(bind)到 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>

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

最好的,

最佳答案

你最好使用 StaticExtension ,像这样:

Uid="{x:Static local:YourClass.ID_foo}"

其中 local 是您类的 C# 命名空间的 xmlns 别名。可以找到更多信息here .

使用 Binding 的问题是你为永远不会改变的东西增加了很多开销。该绑定(bind)将尝试监视您的属性(property)。此外,还有 known "leaks"在未实现 INotifyPropertyChanged 的​​对象上使用具有非依赖属性的绑定(bind)。

关于c# - 在 WPF 中的 xaml 代码中绑定(bind) const 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com