首页 > 解决方案 > RadioButton IsChecked 未绑定到单独的变量

问题描述

作为 XAML 项目的一部分,我在一个组中有两个单选按钮:

<StackPanel HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="0" Margin="20,0,0,0">
    <RadioButton x:Name="XMLViewButton" GroupName="DisplayType" IsChecked="{Binding XmlViewIsChecked, FallbackValue=True, Mode=TwoWay}" Content="XML View" Margin="0,0,5,0"/>
    <RadioButton x:Name="TextViewButton" GroupName="DisplayType" IsChecked="{Binding TextViewIsChecked, FallbackValue=False, Mode=TwoWay}" Content="Text View" Margin="5,0,0,0"/>
</StackPanel>

然后我有一个命令稍后引用这些 IsChecked 绑定:

public void CopyToClipboard(object o)
{
    if (TextViewIsSelected == true)
    {
        Clipboard.SetText(myFile.TextContent);
    }
    else if (XmlViewIsSelected == true)
    {
        Clipboard.SetText(myFile.XMLContent);
    }
}

但是,无论选择哪个单选按钮,它都始终XmlViewIsSelected为 True 且始终为 false。TextViewIsSelected我错过了什么?

标签: c#xamldata-binding

解决方案


我认为您将 XmlViewIsChecked 拼错为 XmlViewIsSelected 以下对我来说正在工作

    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="0" Margin="20,0,0,0">
        <RadioButton x:Name="XMLViewButton" GroupName="DisplayType" IsChecked="{Binding XmlViewIsChecked, FallbackValue=True, Mode=TwoWay}" Content="XML View" Margin="0,0,5,0"/>
        <RadioButton x:Name="TextViewButton" GroupName="DisplayType" IsChecked="{Binding TextViewIsChecked, FallbackValue=False, Mode=TwoWay}" Content="Text View" Margin="5,0,0,0"/>
        <Button Content="Check" Click="Button_Click" />
    </StackPanel>

public partial class MainWindow : Window
{
    public bool XmlViewIsChecked { get; set; }
    public bool TextViewIsChecked { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (TextViewIsChecked)
        {
            Clipboard.SetText("text");
        }
        else if (XmlViewIsChecked)
        {
            Clipboard.SetText("xml");
        }
    }
}

推荐阅读