【发布时间】:2017-06-18 02:33:38
【问题描述】:
我有一个填充了元素的数据网格和每个元素的复选框。
我正在寻找一种方法,让 ViewModel 中的对象成为当前选中复选框的任何元素。
到目前为止,这是我的 XAML:
<Window x:Class="fun_with_DataGridCheckBoxColumns.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:fun_with_DataGridCheckBoxColumns"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Label Content="Chosen One : " />
<Label Content="{Binding ChosenOne.Name, Mode=OneWay}" />
</StackPanel>
<DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID, Mode=OneWay}" IsReadOnly="True"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name, Mode=OneWay}" IsReadOnly="True"/>
<DataGridCheckBoxColumn Header="Is Chosen"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
还有我的 CS:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
namespace fun_with_DataGridCheckBoxColumns
{
public partial class MainWindow : Window
{
public Person ChosenOne { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = new Viewmodel();
}
}
public class Viewmodel : INotifyPropertyChanged
{
public ObservableCollection<Person> People { get; private set; }
private Person _chosenOne = null;
public Person ChosenOne
{
get
{
if (_chosenOne == null) { return new Person { Name = "Does Not Exist" }; }
else return _chosenOne;
}
set
{
_chosenOne = value;
NotifyPropertyChanged("ChosenOne");
}
}
public Viewmodel()
{
People = new ObservableCollection<Person>
{
new Person { Name = "John" },
new Person { Name = "Marie" },
new Person { Name = "Bob" },
new Person { Name = "Sarah" }
};
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Person
{
private static int person_quantity = 0;
private int _id = ++person_quantity;
public int ID { get { return _id; } }
public string Name { get; set; }
}
}
这是我正在寻找的行为:
- ViewModel 中的 ChosenOne 成为选中复选框的任何 Person
- 当一个复选框被选中时,所有其他的都被取消选中
- 如果未选中任何复选框,则将 ChosenOne 设置为 null
基本上,这与我将其放入 DataGrid (XAML) 中的行为相同:
SelectedItem="{Binding ChosenOne, Mode=TwoWay}"
但在我的情况下,ChosenOne 不能成为数据网格的 SelectedItem,因为我需要 SelectedItem 来做其他事情,而且出于公司原因,我必须使用复选框。
我还没有找到如何用复选框模拟这个“SelectedItem”逻辑。
我知道我可以在我的 Person 类中放置一个“bool IsChosen”属性并将复选框绑定到它,但我真的宁愿避免这种情况。如果一切都失败了,这将是我的解决方案。
谢谢。
【问题讨论】:
标签: wpf checkbox data-binding datagrid wpfdatagrid