ItemssourceをDataTemplate内のコンボボックスに動的に設定する方法は?
-
06-07-2019 - |
質問
1つの Listbox
があり、1つの DataTemplate
をこのように適用しました
<ListBox>
<ListBox.ItemTemplate>
<Grid>
<TextBlock Text="{Binding Path=Name}" Grid.Row=0/>
<ComoboBox Name="test"
DisplayMemberPath="Country"
SelectedValuePath="Country_ID">
</Grid>
-
ListBox
で選択された各項目に基づいてItemSource
をこのComboBox
に動的にロードするにはどうすればよいですか?私はWPFを初めて使用しています...貴重なご提案をお待ちしています。
解決
<ListBox>
<ListBox.ItemTemplate>
<Grid>
<TextBlock Text="{Binding Path=Name}" Grid.Row=0/>
<ComoboBox Name="test"
DataContent="{Binding RelativeSource={RelativeSource AncestorType=ListBox}}"
ItemsSource="{Binding}"
DisplayMemberPath="Country"
SelectedValuePath="Country_ID">
</Grid>
今、コンボボックスは常に親リストボックスと同じ項目ソースを持っています。
他のヒント
これを行う1つの方法は、ComboBoxのItemsSourceをListBoxのSelectedValueプロパティにバインドすることです。これを機能させるには、ComboBoxがバインドするアイテムのリストを含むアイテムのコレクションにListBoxをバインドする必要があります。
<ListBox
x:Name="CategoryList"
ItemsSource="{Binding Path=MasterList,
RelativeSource={RelativeSource AncestorType=Window}}"
DisplayMemberPath="MasterProperty"
SelectedValuePath="Details"
/>
<ComboBox
ItemsSource="{Binding Path=SelectedValue, ElementName=CategoryList}"
DisplayMemberPath="DetailProperty"
Grid.Row="1"
/>
この例では、詳細コレクションを含むオブジェクトのリストを公開するウィンドウの背後のコードにパブリックプロパティを作成しました。
public List<Master> MasterList { get; set; }
public class Master
{
public string MasterProperty { get; set; }
public List<Detail> Details { get; set; }
}
public class Detail
{
public string DetailProperty { get; set; }
}
所属していません StackOverflow