1
我有一個具有ContentObject屬性的用戶控件,我用它來指定自定義內容。在我的主窗口上,我創建了一個綁定到依賴項屬性的嵌套標籤。它工作正常,如果我的RelativeSource綁定,但由於某些原因,如果我按名稱引用元素它不工作:無法將ContentPresenter子元素綁定到外部控件的名稱
MainWindow.xaml:
<Window x:Class="TestContentPresenter.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestContentPresenter"
Title="MainWindow" Height="350" Width="525" Name="MyWindow">
<Grid>
<local:MyUserControl>
<local:MyUserControl.ContentObject>
<!--<TextBlock Text="{Binding MyText, ElementName=MyWindow}"/>-->
<TextBlock Text="{Binding MyText, RelativeSource={RelativeSource AncestorType=Window}}"/>
</local:MyUserControl.ContentObject>
</local:MyUserControl>
</Grid>
</Window>
UserControl.xaml:
<UserControl x:Class="TestContentPresenter.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestContentPresenter"
Height="300" Width="300" Name="MainControl">
<StackPanel>
<ContentPresenter Content="{Binding ContentObject, ElementName=MainControl}"/>
</StackPanel>
</UserControl>
主窗口具有MyText依賴項屬性,註釋行不起作用。我懷疑這與名稱範圍有關,但是我做錯了什麼?
如果這是在另一個用戶控件內部使用的,綁定到一個窗口的relativeSource是不恰當的? – Gui