这是我的绑定源对象:

Public Class MyListObject

    Private _mylist As New ObservableCollection(Of String)
    Private _selectedName As String

    Public Sub New(ByVal nameList As List(Of String), ByVal defaultName As String)

        For Each name In nameList
            _mylist.Add(name)
        Next

        _selectedName = defaultName

    End Sub

    Public ReadOnly Property MyList() As ObservableCollection(Of String)
        Get
            Return _mylist
        End Get
    End Property

    Public ReadOnly Property SelectedName() As String
        Get
            Return _selectedName
        End Get
    End Property

End Class

这是我的XAML:

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:local="clr-namespace:WpfApplication1"
        >

    <Window.Resources>
        <ObjectDataProvider x:Key="MyListObject" ObjectInstance="" />
    </Window.Resources>

        <Grid>

        <ComboBox Height="23"
                  Margin="24,91,53,0"
                  Name="ComboBox1"
                  VerticalAlignment="Top"
                  SelectedValue="{Binding Path=SelectedName, Source={StaticResource MyListObject}, Mode=OneWay}"
                  ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}, Mode=OneWay}"
                  />

        <Button Height="23"
                HorizontalAlignment="Left"
                Margin="47,0,0,87"
                Name="btn_List1"
                VerticalAlignment="Bottom"
                Width="75">List 1</Button>

        <Button Height="23"
                Margin="0,0,75,87"
                Name="btn_List2"
                VerticalAlignment="Bottom"
                HorizontalAlignment="Right"
                Width="75">List 2</Button>
    </Grid>
</Window>

以下是代码隐藏:

Class Window1

    Private obj1 As MyListObject
    Private obj2 As MyListObject
    Private odp As ObjectDataProvider

    Public Sub New()

        InitializeComponent()

        Dim namelist1 As New List(Of String)
        namelist1.Add("Joe")
        namelist1.Add("Steve")
        obj1 = New MyListObject(namelist1, "Steve")
.
        Dim namelist2 As New List(Of String)
        namelist2.Add("Bob")
        namelist2.Add("Tim")
        obj2 = New MyListObject(namelist2, "Tim")

        odp = DirectCast(Me.FindResource("MyListObject"), ObjectDataProvider)
        odp.ObjectInstance = obj1

    End Sub

    Private Sub btn_List1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List1.Click

        odp.ObjectInstance = obj1

    End Sub

    Private Sub btn_List2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List2.Click

        odp.ObjectInstance = obj2

    End Sub
End Class

首次加载Window时,绑定很好。 ComboBox包含名称“Joe”。和“史蒂夫”和“史蒂夫”默认选中。但是,当我单击一个按钮将ObjectInstance切换为obj2时,ComboBox ItemsSource会在下拉列表中正确填充,但SelectedValue设置为Nothing而不是等于obj2.SelectedName。

有帮助吗?

解决方案

上周我们遇到了类似的问题。它与 SelectedValue 如何更新其内部结构有关。我们发现如果您设置 SelectedValue ,它将不会看到我们必须改变的设置 SelectedItem ,这将正确地更新每件事。我的结论是 SelectedValue 设计用于获取操作而未设置。但这可能只是当前版本的3.5sp1 .net

中的一个错误

其他提示

激起一场2岁的对话:

如果你想使用字符串,另一种可能性是将它绑定到组合框的Text属性。

<ComboBox Text="{Binding Test}">
     <ComboBoxItem Content="A" />
     <ComboBoxItem Content="B" />
     <ComboBoxItem Content="C" />
</ComboBox>

这就像是:

public class TestCode
{
    private string _test;
    public string Test 
    { 
      get { return _test; }
      set
      {
         _test = value;
         NotifyPropertyChanged(() => Test); // NotifyPropertyChanged("Test"); if not using Caliburn
      }
    }
}

上面的代码是双向的,所以如果你设置Test =&quot; B&quot ;;在代码中,组合框将显示“B”,然后如果从下拉列表中选择“A”,则绑定属性将反映更改。

使用

UpdateSourceTrigger=PropertyChanged 

中的绑定

问题:

ComboBox类使用IndexOf方法搜索指定的对象。此方法使用Equals方法确定相等性。

解决方案:

因此,尝试通过Converter使用SelectedValue设置SelectedIndex,如下所示:

C#代码

//Converter

public class SelectedToIndexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is YourType)
            {
                YourType YourSelectedValue = (YourType) value;

                YourSelectedValue = (YourType) cmbDowntimeDictionary.Tag;
                YourType a = (from dd in Helper.YourType
                                        where dd.YourTypePrimaryKey == YourSelectedValue.YourTypePrimaryKey
                                        select dd).First();

                int index = YourTypeCollection.IndexOf(a); //YourTypeCollection - Same as ItemsSource of ComboBox
            }
            return null;
        }
         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value!=null && value is int)
            {
                return YourTypeCollection[(int) value];
            }

            return null;
        }
    }

<强>的Xaml

<ComboBox 
   ItemsSource="{Binding Source={StaticResource YourDataProvider}}"
   SelectedIndex="{Binding Path=YourValue, Mode=TwoWay, Converter={StaticResource SelectedToIndexConverter}, UpdateSourceTrigger=PropertyChanged}"/>
祝你好运! :)

SelectedValuePath 的类型和 SelectedValue 必须完全相同。

例如,如果 SelectedValuePath 的类型是 Int16 ,并且绑定到 SelectedValue 的属性的类型是 int 它不起作用。

我花了好几个小时才发现这一点,这就是为什么我在这么多时间之后回答问题的问题。也许像我这样有同样问题的另一个可怜的家伙可以看到它。

进入类似的东西,最后我只是订阅了下拉的SelectionChanged事件并用它设置我的数据属性。愚蠢并希望它不需要,但它有效。

设置SelectedValuePath =&quot; Content&quot;是否合理?在组合框的xaml中,然后使用SelectedValue作为绑定?

看来你有一个字符串列表,并希望绑定只是对组合框中的实际项目内容进行字符串匹配,所以如果你告诉它要用于SelectedValue的属性,它应该工作;至少,当我遇到这个问题时,这对我有用。

看起来内容对于SelectedValue来说是一个合理的默认值,但也许不是吗?

您是否尝试过引发SelectName已更新的事件,例如OnPropertyChanged(&quot; SelectedName&quot;)?这对我有用。

在我的情况下,我绑定到一个列表,而我应该绑定到一个字符串。

我在做什么:

private ObservableCollection<string> _SelectedPartyType;

public ObservableCollection<string> SelectedPartyType { get { return 
_SelectedPartyType; } set { 
             _SelectedPartyType = value; OnPropertyChanged("SelectedPartyType"); } }

应该是什么      

 private string _SelectedPartyType;

 public string SelectedPartyType { get { return _SelectedPartyType; } set { 
             _SelectedPartyType = value; OnPropertyChanged("SelectedPartyType"); } }

绑定模式需要是OneWayToSource或TwoWay,因为源是您想要更新的。模式OneWay是源到目标,因此使源ReadOnly导致永远不更新源。

你知道......今天我已经和这个问题争斗了几个小时,你知道我发现了什么吗?这是一个DataType问题!填充ComboBox的列表是Int64,我试图将值存储在Int32字段中!没有错误被抛出,它只是没有存储值!

刚刚解决了这个问题。咦! 要么使用[之一] .SelectedValue | .SelectedItem | .SelectedText 提示:选择的值是ComboStyle.DropDownList的首选,而.SelectedText是ComboStyle.DropDown的首选。

- 这应该可以解决你的问题。我花了一个多星期来解决这个小小的fyn。哈!!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top