【问题标题】:How to have a property of a view model set the height/width for all associate child controls如何让视图模型的属性设置所有关联子控件的高度/宽度
【发布时间】:2011-06-27 03:55:51
【问题描述】:

以下是场景:我有一个 flickr 照片查看器,PhotoBrowserViewModel 有一个名为 Image Source 的属性。绑定到我的 PhotoBrowserViewModel 的视图包含以下 XAML。 我的目标是让子控件具有 ImageSource 属性的高度/宽度。

        <ItemsControl ItemsSource="{Binding Photos}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="viewmodel:FlickrPhotoViewModel">
                    <controls:FlickrPhotoControl Margin="10"/> 
<!-- I want to set this control's Width/Height to {Binding PhotoSize}-->
<!-- on the same data context as ItemsControl, not as the data template.-->
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

【问题讨论】:

    标签: c# .net wpf mvvm binding


    【解决方案1】:

    使用相对源绑定:

    {Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.PhotoSize}
    

    【讨论】:

    • 相对源绑定总是让我不知为何感到肮脏。
    • 大声笑,我不在乎,去做吧! (或者你可以在你的资源中创建一个引用,这样你就可以使用Source={StaticResource MyContext}。你也可以用ElementName做一些事情,例如命名你的窗口并获取它的DataContext)
    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2013-02-07
    • 2017-11-03
    • 2018-05-19
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多