将Window.DataContext设置为代码隐藏中的声明属性?

时间:2009-09-30 01:41:40

标签: wpf xaml properties datacontext code-behind

我希望实现以下内容(注意Window元素的DataContext属性):

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding MyDataContext}"/>

Class Window1 
    Public ReadOnly Property MyDataContext() As IEnumerable(Of String)
        Get
            Return New String() {"Item1", "Item2"}
        End Get
    End Property
End Class

1 个答案:

答案 0 :(得分:1)

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding MyDataContext, RelativeSource={RelativeSource Self}}">
    <Grid>
        <ListBox ItemsSource="{Binding}"/>
    </Grid>
</Window>

我认为使用DependencyProperty可能会更好,它应该很好地同步。

相关问题