2017-05-31 80 views
-2

我已经阅读了所有的地方,该绑定是可以在WPF中实现接口,但我有一段时间实际上得到任何牵引力。我也使用EF Core,如果它可以帮助您准备好我的代码。组合框填充数据,因此数据的绑定工作,但SelectedItem无法绑定,并且选定项目内的文本显示空白。在WPF中为组合框绑定接口SelectedItem

我不明白以下内容如何绑定到实现接口的对象。

的XAML为组合框:

<ComboBox Height="23" x:Name="cbJumpList" Width="177" Margin="2" HorizontalAlignment="Left" 
      IsEditable="False" 
      DisplayMemberPath="Name" 
      SelectedItem="{Binding Path=(model:IData.SelectedJumpList), Mode=TwoWay}" 
      /> 

MainWindow.xaml.cs:

protected IData DB { get; private set; } 
public MainWindow() 
{ 
    InitializeComponent(); 

    DB = new Data.DataSQLite(true); 
    DB.Bind_JumpLists_ItemsSource(cbJumpList); 
} 

IData.cs:

public interface IData : IDisposable, INotifyPropertyChanged 
{ 
    void Bind_JumpLists_ItemsSource(ItemsControl control); 
    IJumpList First_JumpList(); 

    IJumpList SelectedJumpList { get; set; } // TwoWay Binding 
} 

IJumpList.cs

public interface IJumpList 
{ 
    long JumpListId { get; set; } 
    string Name { get; set; } 
} 

然后执行对象(Data.DataSQLite)内:

public void Bind_JumpLists_ItemsSource(ItemsControl control) 
{ 
    control.ItemsSource = null; 

    db.JumpLists.ToList(); 
    control.ItemsSource = db.JumpLists.Local; 
    control.Tag = db.JumpLists.Local; 

    SelectedJumpList = db.JumpLists.FirstOrDefault(); 
} 

public IJumpList SelectedJumpList 
{ 
    get { return _SelectedJumpList; } 
    set 
    { 
     _SelectedJumpList = value; 
     NotifyPropertyChanged(); 
    } 
} 
IJumpList _SelectedJumpList; 

private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") 
{ 
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
} 

我要补充,PropertyChanged事件保持为空。

+0

试图绑定列表从'ToList()返回'到SelectedItem属性?另外'IJumpList'里面是什么? –

+1

@SivaGopal不,ToList正在更新别处绑定中使用的'Items.Local'属性。我想这可能会导致混乱,我会编辑它。 –

回答

0

ComboBoxSelectedItem属性应该绑定到属性而不是类型。对于绑定工作,您还应该将ComboBoxDataContext设置为定义此属性的类型的实例。

试试这个:

<ComboBox Height="23" x:Name="cbJumpList" Width="177" Margin="2" HorizontalAlignment="Left" 
      IsEditable="False" 
      DisplayMemberPath="Name" 
      SelectedItem="{Binding SelectedJumpList}" /> 

public void Bind_JumpLists_ItemsSource(ItemsControl control) 
{ 
    db.JumpLists.ToList(); 
    control.DataContext = this; 
    control.ItemsSource = db.JumpLists.Local; 
    control.Tag = db.JumpLists.Local; 

    SelectedJumpList = db.JumpLists.FirstOrDefault(); 
} 
+1

mm8谢谢。该类型的实例上的'control.DataContext = this;'是关键。更改SelectedItem并不重要。你的方式奏效了,我的工作也是如此。现在我必须努力让它更新我的其他列表,以改变它的影响,但这是一个巨大的颠簸。不能相信某人低估了它,因为它是解决方案。 –