【问题标题】:xaml How to bind to a different source?xaml 如何绑定到不同的源?
【发布时间】:2014-11-03 19:56:55
【问题描述】:

我在 C# 代码中设置了Items,如下所示:

this.DefaultViewModel["Items"] = items;

我已经在xaml 页面中这样定义它:

DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"

现在我可以在GridView 中使用Items

<GridView ItemsSource="{Binding Items}">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Grid Width="{Binding customWidth}">
                <!-- The rest-->
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

但问题是我希望内部网格使用不同的来源:

this.DefaultViewModel["customWidth"] = 300;

如何使内部网格使用与其父 GridView 不同的源?谢谢。

【问题讨论】:

  • 您可以在实例中为任何FrameworkElement设置DataContext

标签: c# xaml windows-phone-8 windows-runtime windows-store-apps


【解决方案1】:

您可以为页面命名(例如,x:Name="myPage"),然后

<GridView ItemsSource="{Binding Items}">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Grid Width="{Binding DefaultViewModel.customWidth, ElementName=myPage}">
                <!-- The rest-->
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

即可以使用 ElementName 走出当前的绑定范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 2016-07-27
    • 2015-09-25
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多