我更喜欢这样做的方式是将IsChecked
绑定到分配给ItemsSource的对象的属性。但在这里我会告诉你的硬盘的方式来做到这一点
(编辑:其实下面是过于复杂对于这种情况,但我会离开这里,现在,看到编辑后)
第一你需要我的VisualTreeEnumeration扩展方法之一: -
public static class VisualTreeEnumeration
{
public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
{
DependencyObject current = VisualTreeHelper.GetParent(root);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
}
现在在我的测试中,我刚刚添加名为lstOutput
一个ListBox
我的XAML。现在,添加以下两个事件给你UserControl
: -
private void rdbIndataGrid_Checked(object sender, RoutedEventArgs e)
{
DataGridRow row = ((DependencyObject)sender).Ancestors().OfType<DataGridRow>().FirstOrDefault();
if (row != null)
lstOutput.Items.Add(String.Format("Checked: {0}", row.DataContext));
}
private void rdbIndataGrid_Unchecked(object sender, RoutedEventArgs e)
{
DataGridRow row = ((DependencyObject)sender).Ancestors().OfType<DataGridRow>().FirstOrDefault();
if (row != null)
lstOutput.Items.Add(String.Format("Unchecked: {0}", row.DataContext));
}
最后调整的单选按钮XAML中,像这样: -
<RadioButton x:Name="rdbIndataGrid" IsChecked="false" GroupName="myGroup"
Checked="rdbIndataGrid_Checked" Unchecked="rdbIndataGrid_Unchecked" />
(其中的一个巧妙的事情有关的XAML连接最多的事件是即使元素是模板的一部分,它也可以工作)。
你会注意到,在事件处理程序中,我正在从发送的RadioButton
的可视树中找到包含DataGridRow
的内容。 DataGridRow
是其DataContext
设置为由该行呈现的对象的对象。在您自己的代码中,您可以将数据上下文值转换为正确的类型,并从那里访问有关该行的其他数据。
编辑
其实在大多数一般情况下,你不需要追捕拥有DataGridRow
对象访问发送RadioButton
的DataContext
属性是足够了: -
private void rdbIndataGrid_Checked(object sender, RoutedEventArgs e)
{
object myData = ((FrameworkElement)sender).DataContext;
if (myData != null)
lstOutput.Items.Add(String.Format("Checked: {0}", myData));
}
private void rdbIndataGrid_Unchecked(object sender, RoutedEventArgs e)
{
object myData = ((FrameworkElement)sender).DataContext;
if (myData != null)
lstOutput.Items.Add(String.Format("Unchecked: {0}", myData));
}
因此,你可以免除Ancestors
扩展方法。但是在更复杂的情况下,DataContext
已被更改,可能需要原来的“过度复杂”方法。