加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:24:12 所属栏目:百科 来源:网络整理
导读:我想将我的一些列表框项目设置为radiobuttons.这是我的代码,但这种风格应用于每个listboxitem. Window.Resources Style TargetType="{x:Type ListBoxItem}" Setter Property="Template" Setter.Value ControlTemplate TargetType="{x:Type ListBoxItem}" Rad
我想将我的一些列表框项目设置为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}" />

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读