Datacontext在Template to Root中使用

时间:2012-11-08 21:12:35

标签: silverlight xaml data-binding datacontext

我希望将数据网格中的按钮显示为可见或折叠,取决于本地窗口属性。

以下项适用于LayoutRoot

<navigation:Page xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="TBPM.PageIssues" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 x:Name="PageIssueRoot"
...

_

        <Grid DataContext="{Binding ElementName=PageIssueRoot}">
            <Button Click="btnPasteMessage_Click" Visibility="{Binding Path=IsSaving, Converter={StaticResource BoolToVis}}" >
                <Grid>
                    <Image Height="24" Source="/Next.png" HorizontalAlignment="Center" />
                </Grid>
            </Button>
        </Grid>

代码隐藏

#Region "IsSaving"

    ''' <summary>
    ''' IsSaving Dependency Property
    ''' </summary>
    Public Shared ReadOnly IsSavingProperty As DependencyProperty = _
        DependencyProperty.Register("IsSaving", GetType(Boolean), GetType(PageIssues), _
            New Windows.PropertyMetadata(False))

    ''' <summary>
    ''' Gets or sets the IsSaving property.  This dependency property 
    ''' indicates ....
    ''' </summary>
    Public Property IsSaving() As Boolean
        Get
            Return CType(GetValue(IsSavingProperty), Boolean)
        End Get
        Set(ByVal value As Boolean)
            SetValue(IsSavingProperty, value)
        End Set
    End Property

#End Region

如果用作DataGrid模板,则不起作用。

解决方案是什么,为什么模板找不到根窗口?

1 个答案:

答案 0 :(得分:0)

尝试RelativeSource绑定...

    <Grid DataContext="{Binding ElementName=PageIssueRoot}">
        <Button Click="btnPasteMessage_Click" Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page} Path=IsSaving, Converter={StaticResource BoolToVis}}" >
            <Grid>
                <Image Height="24" Source="/Next.png" HorizontalAlignment="Center" />
            </Grid>
        </Button>
    </Grid>