微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将某些WPF列表框设置为单选按钮?

我想将我的一些列表框项目设置为radiobuttons.这是我的代码,但这种风格应用于每个listBoxitem.

<Window.Resources>
    <Style targettype="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate targettype="{x:Type ListBoxItem}">
                    <RadioButton Content="{TemplateBinding Content}"
                                 IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent},Path=IsSelected}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

我该怎么做才能让我可以指定一个列表框来设置单选按钮.我想这个名称会是这样的:

<ListBox Name="ListBox1" Width="120" Visibility="Visible" Background="{x:Null}" BorderThickness="0" Style="{StaticResource radioListBox}">

我知道问题的一部分是这只是样式listBoxitems但我不知道如何设置列表框本身的样式.我当然更喜欢添加背景和边框属性.

任何帮助,将不胜感激.

解决方法

你需要给你的风格一把钥匙:

<Window.Resources>
    <Style x:Key="radioListBoxItem" targettype="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate targettype="{x:Type ListBoxItem}">
                    <RadioButton Content="{TemplateBinding Content}"
                                 IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent},Path=IsSelected}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

然后你将它应用于ListBox,如:

<ListBox ItemContainerStyle="{StaticResource radioListBoxItem}" />

如果要为包含无线电列表框项和其他一些属性的ListBox创建样式,您也可以这样做:

<Style x:Key="radioListBox" targettype="{x:Type ListBox}">
    <Setter Property="ItemContainerStyle" Setter="{StaticResource radioListBoxItem}" />
    <Setter Property="Background" Value="Navy" />
</Style>

你会申请它:

<ListBox Style="{StaticResource radioListBox}" />

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐