C# 如何在WPF Mvvm中检索动态生成的单选按钮的选定单选按钮
使用WPF和MVVM模式,我得到了一个动态填充单选按钮的列表框C# 如何在WPF Mvvm中检索动态生成的单选按钮的选定单选按钮,c#,wpf,mvvm,C#,Wpf,Mvvm,使用WPF和MVVM模式,我得到了一个动态填充单选按钮的列表框 <ListBox ItemsSource="{Binding SupportedNtgs}" VerticalAlignment="Stretch" Background="Transparent"> <ListBox.ItemTemplate> <DataTemplate> <Radi
<ListBox ItemsSource="{Binding SupportedNtgs}" VerticalAlignment="Stretch" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="SupportedNtgsRadioButtonList" Content="{Binding Item2}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
列表框绑定到的SupportedNtgs
是一个IEnumerable
public IEnumerable<Tuple<Ntg, String>> SupportedNtgs
{
get
{
if (this.supportedNtgs == null) {
this.supportedNtgs = new List<Tuple<Ntg, string>>();
foreach (var item in this.provider.SupportedNtgs) {
this.supportedNtgs.Add(new Tuple<Ntg, string>(item, EnumHelper<Ntg>.Description(item)));
}
}
return this.supportedNtgs;
}
}
public IEnumerable SupportedNtgs
{
得到
{
if(this.supportedNtgs==null){
this.supportedNtgs=新列表();
foreach(此.provider.SupportedNtgs中的变量项){
this.supportedNtgs.Add(新元组(item,EnumHelper.Description(item));
}
}
返回此.supportedNtgs;
}
}
有谁能告诉我,在不更改Ntg类的情况下,将用户选择存储在SelectedNtg属性中的最简单方法是什么?多谢各位
谢谢你给你
- 使用SelectedNtg
SelectedItem=“{binding SelectedNtg}”
<ListBox ItemsSource="{Binding SupportedNtgs}"
VerticalAlignment="Stretch" Background="Transparent"
SelectedItem="{Binding SelectedNtg}" >
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="SupportedNtgsRadioButtonList"
Content="{Binding Item2}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这将在视图模型中将所选项目推送到您的属性中,因此您将获得您要查找的数据您是否测试了此项?有些东西不起作用,当在SelectedNtg属性的setter中放置断点时,调试器在ui中切换选择时不会停止。只要您在与SupportedNtgs相同的datacontext中有一个名为SelectedNtg的公共属性,调试器就应该起作用。此外,您可以在运行应用程序时检查输出窗格中的任何绑定错误。我有该属性,并且没有输出错误。我还尝试了Mode=TwoWay,但这也不能解决问题。奇怪的是,我注意到你的ienumerable是Tuple类型的,所以也许
SelectedNtg应该是Tuple类型的,看看这是否适合你。我也发现了,如果我按照你的建议更改它,它应该会起作用。但是还有另一个问题:SelectedItem属性将绑定所选项目,而不是选中radiobutton的项目。我认为列表框是用于此目的的错误控件。我将尝试ItemControl,向元组添加一个bool,并将该bool绑定到radiobutton的ischecked属性。
<ListBox ItemsSource="{Binding SupportedNtgs}"
VerticalAlignment="Stretch" Background="Transparent"
SelectedItem="{Binding SelectedNtg}" >
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="SupportedNtgsRadioButtonList"
Content="{Binding Item2}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>