我试图将字典绑定到列表视图中的两个文本块 . listview ItemsSource绑定在后面的代码中定义,文本块内容在XAML中 .
我能够显示项目,但它们在每行周围显示方括号,如[stringA,stringB] . 但是,这种格式不起作用 . 我尝试的最新代码是通过设置不起作用的密钥和值:
XAML:
<ListView Name="lvListLogs"
Margin="0,10,0,0">
<ListView.ItemTemplate>
<DataTemplate x:Name="ListItemTemplate">
<Grid Margin="5,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="122"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition MaxHeight="104"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock x:Name="tb_PointName" Grid.Column="1"
Text="{Binding Key}"
Margin="10,0,0,0" FontSize="40"
TextWrapping="Wrap"
MaxHeight="72"
Foreground="#FFFE5815" />
<TextBlock x:Name="tb_PointValue" Grid.Column="1"
Text="{Binding Value}"
Margin="10,0,0,0" FontSize="40"
TextWrapping="Wrap"
MaxHeight="72"
Foreground="#FFFE5815" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C#(为清晰起见删节):
public Dictionary<string, string> mydict2 { get; set; }
mydict2 = new Dictionary<string, string>();
if (item != null)
{
var props = item.GetType().GetRuntimeProperties();
foreach (var prop in props)
{
foreach (var itm in group1.Items.Where(x => x.UniqueId == prop.Name))
{
var _Title = prop.Name;
var _Value = prop.GetValue(item, null);
string propertyValue;
string propertyName;
propertyValue = Convert.ToString(_Value);
propertyName = _Title;
mydict2.Add(_Title, propertyValue);
}
}
//binding here
lvListLogs.ItemsSource = mydict2;
}
任何援助将不胜感激 .
2 回答
你的代码工作正常,问题是你为
TextBlocks
设置了相同的Grid.Column
. 第一列索引应为零:为了实现所需的绑定,我使用了带有类和构造函数的ObservableCollection而不是Dictionary .
要将listview(xaml)数据绑定到ObservableCollection:
使用构造函数创建类
创建PointInfoClass的集合
实例化集合
添加项目到集合
Databind到ObservableCollection名称 . xaml代码:
设置ListView的DataContext
为清楚起见,编辑此代码 .