【发布时间】:2016-01-08 17:13:18
【问题描述】:
使用 Visual Studio 2015 社区和 .NET 4.5
我有一个特定于我的应用用户的单选按钮的动态列表。当用户使用 Web 服务进行身份验证时,会动态创建按钮列表。列表存储在 ObservableCollection 中。我已将它绑定到 XAML 并正确呈现,并且在选择后正确存储 isSelected。
我想要做的是在用户选择服务类型(单击单选按钮)时触发事件。我已经阅读了很多示例,但它们对单选按钮进行了硬编码,但就我而言,我需要这些按钮是动态的。
如何将 XAML 中的按钮单击绑定到 ViewModel?
ServiceCost.cs
public class ServiceCost
{
public long pst_id { get; set; }
public string pst_description_short { get; set; }
public decimal pst_cost { get; set; }
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set{if (value != _isSelected) { _isSelected = value; } }
}
public string DescriptionPrice
{
get
{
return string.Format(Strings.ServiceCost_DescriptionPrice, this.pst_description_short, pst_cost.ToString());
}
}
...
xaml:
...
<GroupBox
Grid.Row="1"
Grid.ColumnSpan="2"
Grid.Column="2"
FontWeight="Bold"
Header="Select Service Type"
Margin="0,7,0,0"
Padding="2">
<ItemsControl FontWeight="Normal" ItemsSource="{Binding Path=ServiceTypes}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding Path=DescriptionPrice}"
IsChecked="{Binding Path=IsSelected}"
GroupName="ServiceType"
Margin="2,3.5"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</GroupBox>
...
视图模型:
...
private ObservableCollection<ServiceCost> _serviceTypes;
public ObservableCollection<ServiceCost> ServiceTypes
{
get { return _serviceTypes; }
set
{
if (_serviceTypes != value)
{
_serviceTypes = value;
DynamicOnPropertyChanged();
}
}
}
...
【问题讨论】:
标签: c# wpf xaml data-binding radio-button