【发布时间】:2020-12-14 20:35:56
【问题描述】:
我有一个名为“CarEngineItems”的“SelectableItems”对象列表,它有 2 个属性:ItemDescription 和 isSelected。
namespace DTOs
{
class CarEngines : INotifyPropertyChanged
{
public static List<SelectableItem> CarEngineItems { get; set; } = new List<SelectableItem>();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
namespace Models
{
public class SelectableItem : INotifyPropertyChanged
{
public string ItemDescription { get; set; }
public bool IsSelected { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
我使用下面的用户控件为列表中的每个项目创建了一个单选按钮。
<UserControl.Resources>
<SelectableItem:SelectableItem x:Key="vm"></SelectableItem:SelectableItem>
<src:RadioButtonCheckedConverter x:Key="RadioButtonCheckedConverter" />
<CollectionViewSource
Source="{Binding Source={x:Static Application.Current}, Path=ItemDescription}"
x:Key="ListingDataView" />
<DataTemplate x:Key="GroupingHeaderTemplate">
<TextBlock Text="{Binding Path=Name}" Style="{StaticResource GroupHeaderStyle}"/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ItemsControl Name="RadioGroup" AutomationProperties.Name="RadioGroup" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding Path=ItemDescription}"
FlowDirection="RightToLeft"
IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Style="{DynamicResource CustomRadioButton}" Margin="20,0"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
我将此用户控件添加到我的主窗口。
<uc:CommonRadioButtonGroup x:Name="EnginesGroup"></uc:CommonRadioButtonGroup>
在后面的代码中,我将这个用户控件的源代码更新为:
InitializeComponent();
EnginesGroup.RadioGroup.ItemsSource = DTOs.CarEngines.CarEngineItems;
CarEngineItems 是在启动时添加的。
CarEngines.CarEngineItems.Add(new SelectableItem
{
ItemDescription = "V8",
IsSelected = Properties.Settings.Default.Engines.Equals("V8")
});
CarEngines.CarEngineItems.Add(new SelectableItem
{
ItemDescription = "Electric",
IsSelected = Properties.Settings.Default.Engines.Equals("Electric")
});
当前输出结果如下: 启动时,按预期选择默认值V8。
Proper binding happens on startup.
但是在单击组中的下一个项目时,它也被选中。
最终目的是选中一个复选框(动态创建)并在按下按钮(SAVE 按钮)时仅将所选项目更新到属性表。但在这种情况下,选择是针对所有项目进行的。
【问题讨论】:
-
你在哪里给 RadioButton 的组名?
-
我刚刚添加了组名,多选问题已解决。但是我在同一个窗口上三次使用相同的用户控件。如何为每个用户控件实例设置不同的组名?问题是,当我在用户控件中选择一个按钮时,其他按钮都未选中。
-
RadioButton 实例上的 GroupName 属性可以绑定到 SelectableItem 类上的属性,您可以从后面的代码或视图模型中设置该属性。
-
添加了另一个属性项目类型,它用于绑定组名。有效。谢谢你的协助,船长。
标签: c# wpf mvvm radio-button datatemplate