TabItem Content IsEnabled绑定

时间:2018-10-17 07:44:58

标签: c# wpf

我正在使用MVVM模式创建WPF应用程序(至少我正在尝试)。有<TabControl>绑定了ItemsSource,即ObservableCollection<TabModel> TabsTabs具有NameItems属性,其中Items是ControlModel的列表,表示控件。将IsEnabled属性绑定到放置Grid的{​​{1}}时遇到问题。

下面的代码部分展示了我的执行方式:

Items

还有xaml ...

private ObservableCollection<TabModel> tabs;

public ObservableCollection<TabModel> Tabs
{
    get
    {
        if (tabs == null)
        {
            tabs = new ObservableCollection<TabModel>();
            RefreshTabs();
        }
        return tabs;
    }
    set
    {
        tabs = value;
        OnPropertyChanged("Tabs");
    }
}
\\Tab Model
public string Name { get; set; }

private List<ControlModel> items;

public List<ControlModel> Items
{
    get { return items; }
    set
    {
        items = value;
        OnPropertyChanged("Items");
    }
}

部分...      <TabControl Margin="0,100,0,0" ItemsSource="{Binding Tabs,UpdateSourceTrigger=PropertyChanged}"> <TabControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </TabControl.ItemTemplate> <TabControl.ContentTemplate> <DataTemplate> <ScrollViewer VerticalScrollBarVisibility="Hidden"> <Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}"> <!--<Grid Margin="5,5,5,5">--> <ItemsControl ItemsSource="{Binding Items,UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource ControlTemplateSelector}"/> </Grid> </ScrollViewer> </DataTemplate> </TabControl.ContentTemplate>

不起作用。没有错误。此网格始终处于禁用状态。默认情况下为假。

<Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}">

问题是:在我的情况下如何正确绑定private bool isProductEditionEnabled = false; public bool IsProductEditionEnabled { get { return isProductEditionEnabled; } set { isProductEditionEnabled = value; OnPropertyChanged("IsProductEditionEnabled"); } }

1 个答案:

答案 0 :(得分:1)

您位于DataTemplate内部,因此在进行绑定时需要指定父DataContext的位置,如下所示:

<DataTemplate>
    <ScrollViewer VerticalScrollBarVisibility="Hidden">
        <Grid IsEnabled="{Binding Path=DataContext.IsProductEditionEnabled, 
                RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}">
        </Grid>
    </ScrollViewer>
</DataTemplate>