我有一个包含名称和两个复选框的列表视图(名称,男性(复选框),女性(复选框))。我想确保一次只从列表视图中选择一个复选框。
<UserControl.Resources>
<DataTemplate x:Key="datatemp">
<StackPanel Orientation="Horizontal" Width="200" >
<TextBlock Text="{Binding VmName}" Width="129" Visibility="Visible" />
<CheckBox Name="cb" IsThreeState="False" Checked="off_chek_select" IsChecked="{Binding IsCheck, Mode=TwoWay}" Margin="6,0,18,6" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<CheckBox Name="cb1" IsThreeState="False" Checked="ins_chek_select" IsChecked="{Binding IsCheck1, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
在这里,我在listview中使用了 datatemplate 。我无法从datatemplate访问控件以便在check事件上写入。
答案 0 :(得分:0)
进入Tag
属性,您可以引用父元素(在您的情况下是StackPanel
),在代码隐藏中,您可以使用FindName
方法找到元素。
XAML:
<DataTemplate x:Key="datatemp">
<StackPanel x:Name="stackPanel" Orientation="Horizontal" Width="200" >
<TextBlock Text="{Binding VmName}" Width="129" Visibility="Visible" />
<CheckBox Name="cb" Tag="{Binding ElementName=stackPanel}" IsThreeState="False" Checked="off_chek_select" IsChecked="{Binding IsCheck, Mode=TwoWay}" Margin="6,0,18,6" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<CheckBox Name="cb1" Tag="{Binding ElementName=stackPanel}" IsThreeState="False" Checked="ins_chek_select" IsChecked="{Binding IsCheck1, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</StackPanel>
</DataTemplate>
代码隐藏:
private void off_chek_select(object sender, RoutedEventArgs e)
{
var cbSender = sender as CheckBox;
if (cbSender != null)
{
var stackPanel = cbSender.Tag as StackPanel;
if (stackPanel != null)
{
var cb1 = stackPanel.FindName("cb1") as CheckBox;
if (cb1 != null)
{
cb1.IsChecked = !cbSender.IsChecked;
}
}
}
}
private void ins_chek_select(object sender, RoutedEventArgs e)
{
var cbSender = sender as CheckBox;
if (cbSender != null)
{
var stackPanel = cbSender.Tag as StackPanel;
if (stackPanel != null)
{
var cb = stackPanel.FindName("cb") as CheckBox;
if (cb != null)
{
cb.IsChecked = !cbSender.IsChecked;
}
}
}
}
如果您有多个选择,并且在您可以使用RadioButton(msdn)时只应选择一个。
<UserControl.Resources>
<DataTemplate x:Key="datatemp">
<StackPanel Orientation="Horizontal" Width="200" >
<TextBlock Text="{Binding VmName}" Width="129" Visibility="Visible" />
<RadioButton Name="cb" IsThreeState="False" IsChecked="{Binding IsCheck, Mode=TwoWay}" Margin="6,0,18,6" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<RadioButton Name="cb1" IsThreeState="False" IsChecked="{Binding IsCheck1, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>