【问题标题】:Instantiate ViewModel property as element in XAML将 ViewModel 属性实例化为 XAML 中的元素
【发布时间】:2014-11-24 17:31:43
【问题描述】:

我有一个带有 MyGeometry 属性类型为 Geometry 的 ViewModel。

在 XAML 视图中,我有一个 GeometryGroup

我想要以下内容:

<GeometryGroup>
    <EllipseGeometry ... />
    <RectangleGeometry ... />
    <!-- How can I put `MyGeometry` here?
     I'm pretty sure I've seen something similar before -->
</GeometryGroup>

所以,一个广泛的问题是:如何直接在 XAML 中将某些 viewmodel 属性实例化为“独立”元素,而不是将其绑定到其他元素的属性? (当然,如果可能的话)

【问题讨论】:

    标签: wpf xaml data-binding


    【解决方案1】:

    不是很好,但可以:

    <GeometryGroup>
        <EllipseGeometry ... />
        <RectangleGeometry ... />
        <CombinedGeometry Geometry1="{Binding MyGeometry}"/>
    </GeometryGroup>
    

    【讨论】:

    • 这很聪明。作为记录 - 因为它是这里的解决方案原则)似乎唯一具有几何类型依赖属性的内置几何子类型是组合几何。如果不是这种情况,则可以从 Geometry 创建一些子类,并向其添加 Geometry 类型的依赖属性。
    【解决方案2】:

    我认为正确的做法是:

    <GeometryGroup>
        <EllipseGeometry ... />
        <RectangleGeometry ... />
        <MyGeometry Prop1="{Binding Prop1_InViewModel}" Prop2="{Binding Prop2_InViewModel}" ... />
    </GeometryGroup>
    

    其中Prop1_InViewModelProp2_InViewModel 是您的ViewModel 的属性。

    【讨论】:

    • 其实我没有MyGeometry的类型。这是我的 ViewModel 的 Geometry 属性。我想将其添加为GeometryGroup 的元素。
    • 这是否意味着您在编译时不知道 Geometry 的类型?如果是这样,您无法为所有可能的类型创建模板并在运行时通过TemplateSelector 选择模板。
    • MyGeometry 的类型为 StreamGeometry。它是一个 ViewModel 属性。我希望我的 XAML 定义的 GeometryGroup 包含它作为它的孩子之一(其他孩子只是为了给出一般的想法)。
    • 如果你有StreamGeometry,你可以将它绑定到Path.Data。但是在 ViewModel 中构造 View 元素并不是一个好主意。
    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多