我有一个ListView,其中有一个包含单选按钮的列和一个包含复选框的列。我想做的就是将此单选按钮绑定到基于属性的int值的值。
我的ListView看起来像这样:
<ListView x:Name="lvSalesmen" ItemsSource="{Binding}" Margin="311,32,0,244" Grid.ColumnSpan="5">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Path=Id}"/>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding Path=FirstName}"/>
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding Path=LastName}"/>
<GridViewColumn Header="IsResponsible">
<GridViewColumn.CellTemplate>
<DataTemplate>
<RadioButton GroupName="IsResponsible" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="IsSecondary">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
这是我在代码隐藏文件中设置DataContext的地方:
private void Vm_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
lvSalesmen.DataContext = vm.Salesmen;
}
我的ViewModel看起来像这样:
public class DistrictsListViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private List<Salesman> _salesman;
private ISalesmenService _salesmenService = new SalesmenService();
public DistrictsListViewModel()
{
}
public async void GetAllSalesmenWithResponsibilityByDistrictId( int id)
{
Salesmen = await _salesmenService.GetSalesmanReponsibilityByDistrictIdAsync(id);
}
public List<Salesman> Salesmen {
get { return _salesman; }
set {
_salesman = value;
PropertyChanged(this, new PropertyChangedEventArgs("Salesmen"));
}
}
推销员是一个清单,其中Salesman对象如下所示:
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int IsResponsible { get; set; }
public int IsSecondary { get; set; }
我想实现的是检查“ IsResponsible”属性值等于1的行中的单选按钮。一次只能检查一个单选按钮。我通过添加“ GroupName”来实现。 此外,如果IsSecondary-property值等于1,则应在“ IsSecondary”列中选中该复选框。
答案 0 :(得分:1)
您遇到一般类型不匹配的问题。 IsChecked
通常是一个bool
值,但只有int
个值可用。
有两种方法可以解决此问题:
IsResponsible
中将IsSecondary
和bool
的类型更改为GetSalesmanReponsibilityByDistrictIdAsync
IsResponsible
操作中将IsSecondary
和bool
的值内部转换为Get
使用以下任一建议,您就可以将给定值绑定到 WPF 中的IsChecked
,例如:
<RadioButton IsChecked="{Binding IsResponsibleBool, Mode=OneWay}" GroupName="IsResponsible" />
<CheckBox IsChecked="{Binding IsResponsibleBool, Mode=OneWay}"/>
建议2的可能解决方案:
public Boolean IsResponsibleBool
{
get => this.IsResponsbile == 1;
}
public Boolean IsSecondaryBool
{
get => this.IsSecondary == 1;
}