我在wpf中有一个网格视图,在template列中有两个单选按钮和一个按钮.如何访问单选按钮的状态
本文关键字:单选按钮 按钮 一个 何访问 状态 访问 wpf 两个 template 视图 我在 | 更新日期: 2023-09-27 18:20:40
我在wpf中有一个网格视图,在template列中有两个单选按钮和一个按钮。如何在按钮的单击事件中访问单选按钮的状态?
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding TrackingID}" Header="TrackingID" Visibility="Hidden" Width="50" />
<DataGridTextColumn Binding="{Binding UserFullName}" Header="Name" Width="140" />
<DataGridTemplateColumn Width="350">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<RadioButton Width="50" Content="Yes" GroupName="status" />
<RadioButton Width="50" Content="No" GroupName="status" IsChecked="True" />
<Button Width="100" Click="Button_Click">View Details</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
我正在捕捉button_Click()函数中按钮的事件。在这个功能中,我想知道选择了哪个单选按钮。
private void Button_Click(object sender, RoutedEventArgs e)
{
int trackingid = Convert.ToInt32((((FrameworkElement)sender).DataContext as DataRowView)[0].ToString()); //get the tracking id of the request
//(((FrameworkElement)sender).DataContext as RadioButton) //not working
}
请帮忙。
如果您不想使用绑定(如果您的"是/否"纯粹是UI属性或出于任何原因,您仍然可以选择。使用x:Name-smth为您的RadioButton命名,如"YesRadioButton"answers"NoRadiOButton",然后:
为共享容器(RadioButtons
的父容器)调用FinName("YesRadioButton")
。
或
使用ElementName
绑定,即将按钮的标签绑定到任何RadiButtons
的IsChecked
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<RadioButton x:Name="YesRadioButton" Width="50" Content="Yes" GroupName="status" />
<RadioButton x:Name="NoRadioButton" Width="50" Content="No" GroupName="status" IsChecked="True" />
<Button Width="100" Click="Button_Click" Tag="{Binding ElementName='YesRadioButton', Path='IsChecked'}">View Details</Button>
</StackPanel>
然后在您的按钮中单击简单地检查发件人的Tag
属性。
将所需的一切绑定到您的项目,然后将Button
(在sender
中)的DataContext
强制转换为该项目,并检查设置了哪些属性。
在您的点击处理程序中,发送者是按钮。因此,您可以查找父级StackPanel,然后在子级中搜索RadioButtons,并查看哪个IsChecked为true。
然而,根据UI项的确切设置,这是非常脆弱的。
更好的方法是将IsChecked绑定到模型上的属性(或者绑定到DataGridTextColumns中的任何属性)。这样,如果视图发生更改,则不需要调整Click处理程序。