我发现了一些奇怪的东西:我有一个表单,其中包含两个绑定到同一个集合的数据网格。根据Xaml中数据网格的顺序,行为会有所不同。
这按预期工作(存在用于添加的额外行):
<DockPanel>
<DockPanel DockPanel.Dock="Right">
<Label Content="ReadOnlyView" DockPanel.Dock="Top"/>
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />
</DockPanel>
<DockPanel>
<Label Content="EditorView" DockPanel.Dock="Top" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="False" CanUserAddRows="True" />
</DockPanel>
</DockPanel>以这种方式排列xaml让我感到困惑(没有额外的行可供添加)
<DockPanel>
<DockPanel>
<Label Content="EditorView" DockPanel.Dock="Top" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="False" CanUserAddRows="True" />
</DockPanel>
<DockPanel DockPanel.Dock="Right">
<Label Content="ReadOnlyView" DockPanel.Dock="Top"/>
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />
</DockPanel>
</DockPanel>下面是我用来做这个的虚拟ViewModel:
public class PersonsViewModel
{
public PersonsViewModel()
{
Persons = new ObservableCollection<Person>
{
new Person {Name = "Johan"},
new Person {Name = "Dave"},
};
}
public ObservableCollection<Person> Persons { get; private set; }
}
public class Person
{
public string Name { get; set; }
}我的问题是,这种行为的原因是什么?
发布于 2012-12-11 19:51:21
一个很好的问题,约翰!我的猜测是,由于您没有显式地为其提供CollectionViewSource,因此由DataGrid自动生成的cvs将在两者之间共享,因为您引用的是相同的源。
因此,当您发出两个IsReadOnly赋值并作为共享源时,最后一个设置将获胜,这两个DataGrid都会向您显示相同的效果。
为了证实我的猜测,我使用了这段代码,当您提供显式的CollectionViewSource使用时,DataGrids的行为就像您所期望的那样。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<CollectionViewSource Source="{Binding Persons}" x:Key="cvs1" />
<CollectionViewSource Source="{Binding Persons}" x:Key="cvs2" />
</Window.Resources>
<DockPanel>
<DataGrid ItemsSource="{Binding Source={StaticResource ResourceKey=cvs1}}" IsReadOnly="False" CanUserAddRows="True" />
<DataGrid ItemsSource="{Binding Source={StaticResource ResourceKey=cvs2}}" IsReadOnly="True" />
</DockPanel>
</Window>编辑:进一步的测试表明,这种行为可以说是奇怪的!我无法解释为什么这会产生三个只读DG
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="False" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />但这会产生交替的只读和可编辑DG:
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="False" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="True" />
<DataGrid ItemsSource="{Binding Persons}" IsReadOnly="False" />因此,我想上面的CVS最适合描述为解决这种奇怪的行为,这样你就可以实现你真正想要的东西。
编辑2:在更多的true false组合之后,我注意到的唯一一致的事情是,如果DataGrid中的最后一个IsReadOnly设置为True,则所有其他DataGrids都是只读的。但如果最后一项设置为false,则所有其他DataGrids将根据其自己的IsReadOnly设置进行操作。此行为可能是由于此MSDN bit造成的
If a conflict exists between the settings at the DataGrid, column,
or cell levels, a value of true takes precedence over a value of false.https://stackoverflow.com/questions/13808143
复制相似问题