我有一个从代码创建和填充的DataGrid 。当网格第一次显示RadioButton列时,“Include”似乎工作得很好。问题是在我更改排序后 RadioButton不再正常工作。你可以点击它,点击窗口外然后回来,或者事件只是等待,它最终会起作用,但显然它不是真的可用。这是一个简单的例子:
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
InitializeDataGrid();
}
private void InitializeDataGrid()
{
var table = GetTestTable();
var newGrid = new DataGrid
{
CanUserAddRows = false,
CanUserSortColumns = true,
AutoGenerateColumns = true,
ItemsSource = table.AsDataView(),
DataContext = table
};
newGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;
UxRootGrid.Children.Add(newGrid);
}
private static DataTable GetTestTable()
{
DataTable table = new DataTable("name");
table.Columns.Add("Include", typeof (bool));
table.Columns.Add("Number", typeof (int));
for (int i = 0; i < 5; i++)
{
var row = table.NewRow();
row[0] = false;
row[1] = i;
table.Rows.Add(row);
}
return table;
}
void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName != "Include")
{
return;
}
DataTemplate template = GetDataTemplate();
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn
{
Header = "Include",
CellTemplate = template,
CellEditingTemplate = template,
};
e.Column = templateColumn;
}
private static DataTemplate GetDataTemplate()
{
var elementFactory = new FrameworkElementFactory(typeof (RadioButton));
var binding = new Binding("Include")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
elementFactory.SetBinding(ToggleButton.IsCheckedProperty, binding);
elementFactory.SetValue(RadioButton.GroupNameProperty, "BindingGroup");
return new DataTemplate {VisualTree = elementFactory};
}
}
}
这是 Xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Name="UxRootGrid">
</StackPanel>
</Window>
因此,要查看问题:
1. 启动应用程序
2. 单击数字 1 旁边的 RadioButton。
3. 单击“数字”标题两次(按降序排序)。
4. 现在单击 Number 4 旁边的
RadioButton。 5. 注意 Number 1 旁边的 RadioButton 现在被取消选择,但 Number 4 旁边的 RadioButton 没有被选中。
6. 单击数字 4 旁边的 RadioButton 几次。最终它会被选中。
更新:我让我的另一个同事在他的机器上尝试了这个,他花了一两个时间排序/选择单选按钮才能看到问题发生,但最终他和我的位置相同。
我对 WPF 很陌生,所以我希望这只是我的一个简单错误。在获得解决方法或其他设置方法方面的任何帮助将不胜感激。