添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Describe the bug
When we set a DataContext to a TabItem , its logical child (set in TabItem.Content ) doesn't inherit it. The DataContext of the logical child remains that of TabItem 's parent.

To Reproduce
Consider the following trivial ViewModels:

public class MainViewModel
    public ChildViewModel ChildViewModel { get; } = new();
public class ChildViewModel
    public string Foo => "Hello World!";

Let's try and bind to Foo from TabItem's child:

<Window>
    <Window.DataContext>
        <core:MainViewModel/>
    </Window.DataContext>
    <TabControl>
        <TabItem Header="Broken tab item"
                 DataContext="{Binding ChildViewModel}">
            <!-- this binding does not work -->
            <TextBlock Text="{Binding Foo}" />
        </TabItem>
        <TabItem Header="Working tab item">
            <!-- this binding works -->
            <TextBlock Text="{Binding ChildViewModel.Foo}" />
        </TabItem>
    </TabControl>
</Window>

Expected behavior
When a DataContext is set to a TabItem , the element set in TabItem.Content inherits the DataContext.

Screenshots

Desktop

  • OS: Windows 11 (but presumably every other?)
  • Avalonia version: 0.10.19 (first spotted in 0.10.14)
  • Additional context

  • There are no warnings in Avalonia's log-to-trace output.
  • Copy-pasting the above XAML into a WPF project works out of the box; both tab items display the text.
  • Seeing the same thing - I was wondering if this was a design choice for TabItem (for the DataContext prop to apply to only the TabItem but not to contents).

    Right now, the workaround is to set the DataContext for the contents (usually a Grid):

    <TabItem Header="My tab item">
        <Grid DataContext="{Binding ChildViewModel}">
            <TextBlock Text="{Binding Foo}" />
        </Grid>
    </TabItem>

    or in both places if you also need it for header binding:

    <TabItem Header="{Binding Header}" DataContext="{Binding ChildViewModel}">
        <Grid DataContext="{Binding ChildViewModel}">
            <TextBlock Text="{Binding Foo}" />
        </Grid>
    </TabItem>
    public class ChildViewModel
        public string Header => "My tab item";
        public string Foo => "Hello World!";