有没有什么好的方法可以将属性绑定到代码隐藏中的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)
我选择这种方式的原因如下:
但是,在维护方面,内部标识符应该在一个地方定义,如下所示:
//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 已知存在"泄漏".
| 归档时间: |
|
| 查看次数: |
12931 次 |
| 最近记录: |