获取ItemsControl MVVM中的当前项目



我用字典中的一些键列表填充ItemsControl,并建议用户将打印在Label中的每个键与下面的ComboBox中的一些值进行映射。

最后,为了填充字典值,我必须获取ComboBox中所选值对应的Label键。

我的所有控件都以MVVM模式绑定到ViewModel属性

<ItemsControl x:Name="icMapping"
HorizontalAlignment="Center" MaxHeight="120"
ItemsSource="{Binding ColumnsMapping}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Center" Margin="6">
<Label x:Name="lblPropertyKey"
Content="{Binding ApiPropertyKey}"
Width="250"/>
<ComboBox x:Name="cboxCsvHeaders"
Width="250"
ItemsSource="{Binding
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window},
Path=DataContext.CsvTemplateFile.CsvHeaders}"
SelectedItem="{Binding
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window},
Path=DataContext.SelectedCsvHeader, Mode=OneWayToSource}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>

我试图循环使用ItemsControl中的ItemsTemplate,但我使用了ComboBox。绑定了SelectedItem中的值后会填充文本。

private string selectedCsvHeader;
public string SelectedCsvHeader
{
get => selectedCsvHeader;
set
{
selectedCsvHeader = value;
if (value != null)
{
var ic = this.configView.icMapping;
for (int i = 0; i < ic.Items.Count; i++)
{
System.Windows.Controls.ContentPresenter cp = (System.Windows.Controls.ContentPresenter)ic.ItemContainerGenerator.ContainerFromItem(ic.Items[i]);
System.Windows.Controls.ComboBox cbox = cp.ContentTemplate.FindName("cboxCsvHeaders", cp) as System.Windows.Controls.ComboBox;
System.Windows.Controls.Label lbl = cp.ContentTemplate.FindName("lblPropertyKey", cp) as System.Windows.Controls.Label;
MessageBox.Show((cbox.Text == selectedCsvHeader).ToString()); // False
}
FillDgPreview();
}
OnPropertyChanged(nameof(SelectedCsvHeader));
}
}

我使用ItemsControl是因为我事先不知道字典里有多少密钥。(在互联网上搜索后(这里有一张解释的图片

提前感谢!

为了设置字典条目的值,您必须使用一个允许更改其Key/Value对条目的Value属性的字典类。

由于Dictionary<TKey,TValue>不允许这样做(因为KeyValuePair<TKey,TValue>是不可变的(,您可以编写自己的字典类,可能比本例中更复杂:

public class KeyValue
{
public KeyValue(string key, string value = null)
{
Key = key;
Value = value;
}
public string Key { get; }
public string Value { get; set; }
}
public class ViewModel
{
public List<KeyValue> Map { get; } = new List<KeyValue>();
public List<string> Keys { get; } = new List<string>();
}

现在,您可以像下面显示的XAML中那样绑定该视图模型,其中{Binding Key}{Binding Value}使用字典条目(即Map集合元素(作为源对象。如果您使用的是具有不同条目类型的自定义字典类,则这些绑定看起来会有所不同。

<ItemsControl ItemsSource="{Binding Map}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}"/>
<ComboBox SelectedItem="{Binding Value}"
ItemsSource="{Binding DataContext.Keys,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

最新更新