我正在尝试在列表视图中生成包含组合框的WPF模式。 组合框将动态生成并需要绑定。
<ListView Height="291" HorizontalAlignment="Left" Margin="12,196,0,0" Name="filterByList" VerticalAlignment="Top" Width="303" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="0,50,34,0" Name="filterName" Text="{Binding DisplayName}" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,50,34,0" Name="filterValues" VerticalAlignment="Top" Width="107" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=filterByValues}" IsEnabled="True" SelectedIndex="0" SelectedValuePath="filterByValues" DisplayMemberPath="filterByValues" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
List<Dimension> dimensionsData = new List<Dimension>();
List<filterByValues> filterByValuesData = new List<filterByValues>();
JArray filterByObject = JArray.Parse("[ { 'DisplayName': 'Fund', 'Values': [ 'FundA', 'FundB', 'FundC' ] }, { 'DisplayName': 'Sector', 'Values': [ 'SectorA', 'SectorB', 'SectorC' ] }, { 'DisplayName': 'Country', 'Values': [ 'CountryA', 'CountryB', 'CountryC' ] } ]");
foreach (JObject value in filterByObject)
{
filterByValuesData = new List<filterByValues>();
String JsonName = (String)value.GetValue("JsonName");
String DisplayName = (String)value.GetValue("DisplayName");
JArray Values = (JArray)value.GetValue("Values");
foreach (var item in Values)
{
filterByValuesData.Add(new filterByValues((string)item));
}
dimensionsData.Add(new Dimension { DisplayName = DisplayName, filterByValues = filterByValuesData });
}
filterByList.ItemsSource = dimensionsData;
public class Dimension
{
public string DisplayName { get; set; }
public List<filterByValues> filterByValues { get; set; }
}
public class filterByValues{
public string filter{ get; set; }
public filterByValues(String val) {
filter = val;
}
}
生成的组合框为空。我是C#和WPF的新手。
答案 0 :(得分:1)
看起来问题出现在ComboBox
的绑定表达式中<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,50,34,0" Name="filterValues" VerticalAlignment="Top" Width="107" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=filterByValues}" IsEnabled="True" SelectedIndex="0" SelectedValuePath="filterByValues" DisplayMemberPath="filterByValues" />
您不需要在项目源中使用相对源绑定,DataTemplate将应用于正在呈现的所有项目。你可以尝试
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,50,34,0" Name="filterValues" VerticalAlignment="Top" Width="107" ItemsSource="{Binding filterByValues}" IsEnabled="True" SelectedIndex="0" SelectedValuePath="filter" DisplayMemberPath="filter" />
如果它仍然不起作用,请查看Visual Studio输出窗口,它会详细输出绑定错误。如果是这种情况,你可以在这里分享。