在使用这些类型时,我对数据绑定是如何工作的感到有点困惑。
我读到过你不能做以下事情
public partial class Window1 : Window
{
public ObservableCollection<string> Items { get; private set; }
public Window1()
{
Items = new ObservableCollection<string>() { "A", "B", "C" };
DataContext = this;
InitializeComponent();
}
}
<Window x:Class="WpfApplication25.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ComboBox>
<ComboBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Items}"/>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</Window>因为CompositeCollection没有数据上下文的概念,所以它内部使用绑定的任何东西都必须设置Source属性。如下所示:
<Window x:Class="WpfApplication25.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<CollectionViewSource x:Key="list" Source="{Binding Items}"/>
</Window.Resources>
<ComboBox Name="k">
<ComboBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource list}}"/>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</Window>但这是如何工作的呢?它将源设置为某个东西,但是那个东西,在本例中,CollectionViewSource使用了一个数据上下文(因为它没有显式地设置源)。
那么,因为"list“是在Window的资源中声明的,这是否意味着它会获得Window DataContext?在这种情况下,为什么下面的方法不起作用?
<Window x:Class="WpfApplication25.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Button x:Key="menu" Content="{Binding Items.Count}"/>
</Window.Resources>
<ComboBox Name="k">
<ComboBox.ItemsSource>
<CompositeCollection>
<ContentPresenter Content="{Binding Source={StaticResource menu}}"/>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
</Window>发布于 2013-07-11 22:07:01
你说得对,CompositeCollection没有datacontext的概念,所以它不能从它的父类继承它。
来自MSDN:
CompositeCollection can contain items such as strings, objects, XML nodes, elements, as well as other collections. An ItemsControl uses the data in the CompositeCollection to generate its content according to its ItemTemplate. For more information about using ItemsControl objects to bind to collections, see the Binding to Collections section of the Data Binding Overview.
回答你的问题
But how is that working? it sets the source to something, but that something, in this case a CollectionViewSource uses a DataContext (as its not explicitly setting a source).
我想你可能想多了,Collection DependecyProperty可以绑定到任何IEnumerable类型,所以只要它创建并实现了IEnumerable,那么集合是如何创建的并不重要。
在本例中,CVS从窗口继承DataContext,然后绑定到Items。
关于你的第二个例子,它不起作用是因为ContentPesenter需要dataContext才能工作,所以由于它可以继承它,绑定机制只是将自己设置为dataContext即使你尝试将内容Source绑定到按钮,你忘记设置路径,我猜这就是为什么它被忽略的原因。你要做的就是把它设置成这样:
<ContentPresenter Content="{Binding Source={StaticResource menu}, Path=Content}"/https://stackoverflow.com/questions/16702914
复制相似问题