WPF绑定到绑定的元素

时间:2014-09-09 06:52:37

标签: c# wpf data-binding

我在视图模型中有一个枚举,在xaml中有一个组合框

<TextBlock>Profession</TextBlock>                     
<TextBox Name="txtSpec" Text="{Binding Speciality}" />
<ComboBox Name="cmbSpec" SelectedIndex="{Binding ElementName=txtSpec, Path=Text, Converter={StaticResource EnumConverter}, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}">
    <ComboBoxItem>Software engineer</ComboBoxItem>
    <ComboBoxItem>Mechanic</ComboBoxItem>
</ComboBox>

txtSpec绑定专业。当组合框选择发生变化时,txtSpec的文本会发生变化,但不会通知该属性已更改。我无法确定对象是否脏。 我的代码有什么问题?感谢。

我通过

解决了这个问题
<Window.Resources>
    <local:Converter x:Key="EnumConverter" />
</Window.Resources>
...

<ComboBox Name="cmbSpec" SelectedIndex="{Binding Speciality, Converter={StaticResource EnumConverter}}">
    <ComboBoxItem>Software engineer</ComboBoxItem>
    <ComboBoxItem>Mechanic</ComboBoxItem>

</ComboBox>

...

[ValueConversion(typeof(object), typeof(string))]
public class Converter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (int)((Specialist)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (Specialist)value;
    }
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过 TwoWay 绑定模式

SelectedIndex="{Binding ElementName=txtSpec, Path=Text, Mode=TwoWay"}

答案 1 :(得分:0)

您是否尝试将SelectedIndex简单地绑定到Speciality

<TextBlock>Profession</TextBlock>                     
<TextBox Name="txtSpec" Text="{Binding Speciality}" />
<ComboBox Name="cmbSpec" SelectedIndex="{Binding Speciality, Converter={StaticResource EnumConverter}}">
    <ComboBoxItem>Software engineer</ComboBoxItem>
    <ComboBoxItem>Mechanic</ComboBoxItem>
</ComboBox>

在我看来,这是实现同一目标的一种更直接的模式。