当控件在UserControl中时,如何通过元素名称绑定?

时间:2014-06-29 02:46:19

标签: xaml data-binding windows-runtime winrt-xaml

我尝试使用元素名称将Fill的{​​{1}}属性绑定到页面Rectangle中的属性,但因为{{1}在DataContext中找不到页面,因此不会发生绑定。

简化示例:

Rectangle

1 个答案:

答案 0 :(得分:0)

实现它的简单方法是使ViewModel成为一个StaticResource,例如在App.xaml中(可以在你的Page.xaml中工作):

<App.Resources>
    <ViewModel:PageViewModel x:Key="MyPageViewModel" />
</App.Resources>

然后在你的Page.xaml:

中引用它
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:Converters_Theme="using:ProjectName.Common.Converters"
    xmlns:CustomControls="using:ProjectName.CustomControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:ProjectName.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ViewModel="using:ProjectName.ViewModels"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="ProjectName.Views.TestPage"
    x:Name="pageName"
    DataContext="{StaticResource MyPageViewModel}"
    mc:Ignorable="d">

    <Page.Resources>
        <Converters_Theme:ThemeColorToSolidColorBrushConverter x:Key="ThemeColorToSolidColorBrushConverter"/>
        <DataTemplate x:Key="ItemDataTemplate">
            <StackPanel Orientation="Vertical">
                <!-- ... -->
                <Rectangle Fill="{Binding Theme.Color, Source={StaticResource MyPageViewModel}, Converter={StaticResource ThemeColorToSolidColorBrushConverter}}" MinHeight="40" MinWidth="40" />
                <!-- ... -->
            </StackPanel>
        </DataTemplate>
    </Page.Resources>

    <Grid>
        <CustomControls:Tab>
            <CustomControls:Tab.LeftContent>
                <ItemsControl ItemsSource="{Binding Items}" ItemTemplate="{StaticResource ItemDataTemplate}" />
            </CustomControls:Tab.LeftContent>
            <CustomControls:Tab.RightContent>
                <!-- ... -->
            </CustomControls:Tab.RightContent>
        </CustomControls:Tab>
    </Grid>
</Page>

为了更清洁地执行此操作,我建议您将ViewModelLocator用作app中的静态资源,这将是所有ViewModel的属性,并使其成为App.xaml中的StaticResource。在App.xaml中实例化一个类比在每个ViewModel中更清晰。

相关问题