3 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
我在Silverlight中遇到了相對(duì)來源的問題。搜索和閱讀后,如果不使用其他綁定庫,我找不到合適的解決方案。但是,這是通過直接引用您知道數(shù)據(jù)上下文的元素來獲得對(duì)父DataContext的訪問的另一種方法。它使用Binding ElementName和工作的很好,只要你尊重自己的命名,不具備重重用templates/ styles跨組件:
<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content={Binding MyLevel2Property}
Command={Binding ElementName=level1Lister,
Path=DataContext.MyLevel1Command}
CommandParameter={Binding MyLevel2Property}>
</Button>
<DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
如果你把按鈕進(jìn)入這也適用Style/ Template:
<Border.Resources>
<Style x:Key="buttonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Button Command={Binding ElementName=level1Lister,
Path=DataContext.MyLevel1Command}
CommandParameter={Binding MyLevel2Property}>
<ContentPresenter/>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Border.Resources>
<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding MyLevel2Property}"
Style="{StaticResource buttonStyle}"/>
<DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
最初,我認(rèn)為x:Names無法從模板項(xiàng)中訪問父元素,但是由于找不到更好的解決方案,因此我嘗試了一下,并且工作正常。

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
我正在搜索如何在WPF中執(zhí)行類似操作,并且得到了以下解決方案:
<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding}"
Command="{Binding Path=DataContext.CustomCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
我希望這對(duì)其他人也有用。我有一個(gè)自動(dòng)設(shè)置為ItemsControls的數(shù)據(jù)上下文,該數(shù)據(jù)上下文具有兩個(gè)屬性:MyItems-這是一個(gè)集合-和一個(gè)命令'CustomCommand'。由于ItemTemplate使用DataTemplate,DataContext無法直接訪問上層的。然后,獲取父級(jí)DC的解決方法是使用相對(duì)路徑并按ItemsControl類型進(jìn)行過濾。

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
RelativeSource與ElementName
這兩種方法可以達(dá)到相同的結(jié)果,
相對(duì)榨汁
Binding="{Binding Path=DataContext.MyBindingProperty,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
此方法在可視樹中查找Window類型的控件(在此示例中),找到它后,您基本上可以DataContext使用來訪問它Path=DataContext....。關(guān)于此方法的優(yōu)點(diǎn)是,您無需與名稱綁定,并且名稱是動(dòng)態(tài)的,但是,對(duì)可視化樹所做的更改可能會(huì)影響此方法,甚至可能破壞該方法。
元素名稱
Binding="{Binding Path=DataContext.MyBindingProperty, ElementName=MyMainWindow}
這個(gè)方法指的是一個(gè)固體靜態(tài)對(duì)象Name,只要您的示波器可以看到它就可以了,您應(yīng)該堅(jiān)持使用命名約定,不要破壞該方法。該方法很簡單,您需要指定一個(gè)Name="..."代表您的Window / UserControl。
盡管這三種類型(RelativeSource, Source, ElementName)都可以執(zhí)行相同的操作,但是根據(jù)下面的MSDN文章,每種類型最好在各自的專業(yè)領(lǐng)域中使用。
在頁面底部的表中找到每個(gè)內(nèi)容的簡要說明以及指向更多詳細(xì)信息的鏈接。
添加回答
舉報(bào)