![](/img/trans.png)
[英]Access ViewModel's ObservableCollection from ContentTemplate while Binding with View
[英]WPF access parent ViewModel from inside a ContentTemplate
我有一個包含模板內容的TabControl,如下所示:
<TabControl x:Name="Items" SelectedItem="{Binding ActiveItem}" TabStripPlacement="Left" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1">
<TabControl.ItemContainerStyle>
<!--Some style stuff-->
</TabControl.ItemContainerStyle>
<TabControl.Template>
<ControlTemplate TargetType="{x:Type TabControl}">
<!--Some structure stuff including a tabpanel and contentPresenter-->
</ControlTemplate>
</TabControl.Template>
<TabControl.ContentTemplate>
<DataTemplate>
<Button x:Name="MyButton" Visibility="{Binding x}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
包含此TabControl的視圖使用類似於以下內容的ViewModel:
public class MyPageViewModel : ScreenConductorViewModelBase<IMyTab>
{
public Visibility x = Visibility.Hidden;
}
我希望模板中按鈕的可見性從我的parent(?)ViewModel中拉出,但是它試圖從項目viewModel中檢索x。
這對我來說很有意義,但是我不確定如何指定該字段應來自父級。
我已經嘗試了一些方法,但是似乎都不起作用:
{Binding x}
{Binding DataContext.x}
{Binding RelativeSource={RelativeSource TemplatedParent}, Path=x}
我確定這樣做一定很簡單,但是我似乎無法解決綁定語法
嘗試
<Button x:Name="MyButton"
Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabControl}},
Path=DataContext.x}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.