【问题标题】:Changing the User Control by binding通过绑定更改用户控件
【发布时间】:2013-03-17 08:37:33
【问题描述】:

我有两个UserControl's

根据我的 ViewModel 中的值,我希望每次显示另一个 UserControl。

他们应该坐在包裹着他们的UserControl

我该怎么做?

这里是包装器:

<UserControl>
    <local:UserControl1></local:UserControl1>// I want it to change by a binding
</UserControl>

【问题讨论】:

    标签: wpf binding user-controls


    【解决方案1】:

    使用 DataTrigger 执行此操作。这是记忆中的,但可能会对您有所帮助:

    <ContentControl>
        <ContentControl.Style>
            <Style TargetType="ContentControl">
                <Setter Property="Content">
                    <Setter.Value>
                        <local:UserControl1 />
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding BoolProperty}" Value="True">
                        <Setter Property="Content">
                            <Setter.Value>
                                <local:UserControl2 />
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
    

    【讨论】:

    • 可能需要在 Style 中添加 TargetType。我使用这个 Surface RT 的屏幕键盘输入了整个答案。不容易! ?
    • 还有一个问题,这一行的 TargetType 应该是什么:&lt;Style&gt;?当我执行UserControl 时,它给了我一个错误。
    • TargetType 将是ContentControl
    【解决方案2】:

    您可以在 ViewModel 中拥有一个布尔属性 BoolProperty,并且基于该值,您可以使用 BooleanToVisibilityConverter 切换其他控件的可见性 -

    <UserControl>
        <UserControl.Resources>
           <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        </UserControl.Resources>
        <local:UserControl1 Visibility="{Binding BoolProperty, Converter=
                                    {StaticResource BooleanToVisibilityConverter}}"/>
    </UserControl>
    

    只要BoolProperty 的值为true,您的控件将为visible,如果falsecollapsed

    【讨论】:

    • 我想了想,有没有办法改变对象本身?
    • change the object itself 是什么意思?
    • 我的意思是我不会拿着两个对象然后一个会出现,两个隐藏。我想持有一个对象并改变它的类型,可以吗?
    • @HodayaShalom 您是否考虑过使用针对您的特定类类型的 DataTemplates?例如,如果您有一个显示宠物的列表框,并且您想为猫和狗指定不同的视图/用户控件,您可以有一个针对猫的 DataTemplate 和一个针对狗的不同的 DataTemplate。这是一个简单而人为的例子:stackoverflow.com/questions/15000771/…
    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多