我有一个 MainWindow.xaml 文件:
<Window.Resources>
<CollectionViewSource x:Key="cvs"
Source="{Binding Source={StaticResource ResourceKey=DetailsCollection}}" />
<CollectionViewSource x:Key="DetailScopes">
<CollectionViewSource.Source>
<ObjectDataProvider
MethodName="GetValues"
ObjectType="{x:Type system:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="entities:DetailScope" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</CollectionViewSource.Source>
</CollectionViewSource>
<DataTemplate x:Key="AccountDetail"
DataType="{x:Type entities:AccountDetail}">
<DockPanel>
<ComboBox
DockPanel.Dock="Left"
ItemsSource="{Binding Source={StaticResource ResourceKey=DetailScopes}}"
SelectedItem="{Binding Path=Scope}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Converter={StaticResource DetailScopeConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Text="{Binding Path=Value}" />
</DockPanel>
</DataTemplate>
</Window.Resources>
...
<ListBox
ItemTemplate="{StaticResource ResourceKey=AccountDetail}"
ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}" />
及其代码隐藏类,我在其中定义了详细范围的过滤器:
public class MainWindow
{
public MainWindow()
{
CollectionViewSource detailScopes;
InitializeComponent();
// Attach filter to the collection view source
detailScopes = this.Resources["DetailScopes"] as CollectionViewSource;
detailScopes.Filter += new FilterEventHandler(DetailScopesFilter);
private void DetailScopesFilter(object sender, FilterEventArgs e)
{
DetailScope scope;
scope = (DetailScope)e.Item;
if (scope == DetailScope.Private ||
scope == DetailScope.Business)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
}
}
接下来是AccountDetail
类:
public class AccountDetail
{
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public DetailScope Scope
{
get { return scope; }
set { scope = value; }
}
private string value;
private DetailScope scope;
}
最后,一个枚举:
public enum DetailScope
{
Private,
Business,
Other
}
当我运行我的代码时,我得到一个列表框,其中填充了一堆帐户详细信息,每个都有自己的组合框,其中包含选定的范围和一个具有适当值的文本框。问题是组合框中的所有选定值都与为最后输入的详细信息设置的范围相匹配,并且更改任何组合框值都会更新所有这些值,就好像它们都绑定到相同的帐户详细信息一样。
当我ObjectDataProvider
从CollectionViewSource
DetailScopes 中取出并将其直接绑定到 AccountDetail 中的组合框ItemsSource
时DataTemplate
,问题就消失了。但是,我确实需要它,CollectionViewSource
因为我正在对其应用一些过滤,而我无法将过滤应用于ObjectDataProvider
.
有人可以解释为什么会发生这种情况以及我实际上应该如何连接CollectionViewSource
和ObjectDataProvider
?谢谢你。