简体   繁体   English

如何将WPF控件动态地更改为另一个?

[英]How I can dynamically change a WPF control into another?

I need to do a component where checkboxes change into radiobuttons when certain property changes. 我需要做一个组件,当某些属性更改时,复选框会变为单选按钮。 I have no idea how to do that kind of change in xaml. 我不知道如何在xaml中进行这种更改。 The checkbox is in a datatemplate as shown below. 复选框位于数据模板中,如下所示。 Now I just need some kind of logic to change it into a radiobutton. 现在,我只需要某种逻辑即可将其更改为单选按钮。

<DataTemplate>
    <CheckBox IsChecked="{Binding IsSelected.Value, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>

Especially when there are a lot of instances, the solution of having both controls within the DataTemplate and changing visibility might not be ideal considering performance and memory usage. 特别是在有很多实例的情况下,考虑到性能和内存使用情况,在DataTemplate同时包含两个控件和更改可见性的解决方案可能不是理想的选择。 In this case, a DataTemplateSelector might do the trick - see this tutorial 在这种情况下,DataTemplateSelector可以解决问题-请参阅本教程

you can put both CheckBox and RadioButton in one container ( StackPanel for example) in DataTemplate and just collapse one of them according to your condition using DataTrigger . 您可以将CheckBoxRadioButton都放在DataTemplate一个容器(例如StackPanel )中,然后使用DataTrigger根据您的条件折叠其中之一。

i hope it'll help you. 希望对您有帮助。 sorry for my pure english. 对不起,我纯正的英语。

<DataTemplate>
    <StackPanel>
        <CheckBox Content="CheckBoxHeader">
            <CheckBox.Style>
                <Style TargetType="CheckBox">
                    <Setter Property="Visibility" Value="Visible"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Condition}" Value="True">
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </CheckBox.Style>
        </CheckBox>
        <RadioButton Content="RadioButtonHeader">
            <RadioButton.Style>
                <Style TargetType="RadioButton">
                    <Setter Property="Visibility" Value="Collapsed"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Condition}" Value="True">
                            <Setter Property="Visibility" Value="Visible"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </RadioButton.Style>
        </RadioButton>                        
    </StackPanel>
</DataTemplate>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM