C# 如何在ItemSource外部绑定DataGridComboxColumn
我正在开发我的第一个“生产”WPF应用程序,我遇到了一个问题。 我有一些代码类似于下面的示例。我遇到的问题是无法填充组合框。我假设这是因为网格的ItemsSource正在“阻止”ComboBox查看ViewModel上的Tasks集合,但我只是猜测。其他一切都正确地进行了数据绑定 我搜索了一下,发现了一个问题;这听起来和我想做的完全一样,但对我来说不起作用 知道为什么我不能让组合框填充吗 型号:C# 如何在ItemSource外部绑定DataGridComboxColumn,c#,wpf,xaml,data-binding,datagrid,C#,Wpf,Xaml,Data Binding,Datagrid,我正在开发我的第一个“生产”WPF应用程序,我遇到了一个问题。 我有一些代码类似于下面的示例。我遇到的问题是无法填充组合框。我假设这是因为网格的ItemsSource正在“阻止”ComboBox查看ViewModel上的Tasks集合,但我只是猜测。其他一切都正确地进行了数据绑定 我搜索了一下,发现了一个问题;这听起来和我想做的完全一样,但对我来说不起作用 知道为什么我不能让组合框填充吗 型号: public class Activity{ public int Id { get; set;
public class Activity{
public int Id { get; set; }
public string Title { get; set; }
public Task Task { get; set; }
}
public class Task{
public int Id { get; set; }
public string Title { get; set; }
}
视图模型:
public ApprovalViewModel{
public ObservableCollection<Activity> Activities { /* ... property logic */ }
public ObservableCollection<Task> Tasks { /* ... property logic */ }
}
问题所在的位置是正确的,绑定是相对于活动的。因此,它正在寻找Activity.Tasks 你链接到的帖子有正确的方法,你只需要根据你的情况调整它
ItemsSource="{Binding Path=DataContext.Tasks, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
这将返回可视化树,查找具有DataContext.Tasks属性的窗口
您的代码示例是否在窗口中?如果没有,您将需要更改{x:Type},其次是在这个对象上设置了DataContext吗?如果没有,您需要将其设置为您的ViewModel。谢谢,工作非常好!我必须将x:Type设置为UserControl。我也很困惑,现在仍然如此,因为FindAncestor并没有出现在Intellisense中。但它似乎奏效了。
<ComboBox
ItemsSource="{Binding Path=DataContext.Tasks,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}}"
SelectedValue="{Binding Task.Title}"
SelectedValuePath="Title"
DisplayMemberPath="Title"/>
ItemsSource="{Binding Path=DataContext.Tasks, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"