Markus
Markus

Reputation: 3375

Binding to property in code

Ok, so I know that there are a lot of questions like this, but none of them seem to help me.

So I have a property that I wan't to use to set the visibility of a TabItem (so I'm not interested in updates of the property).

The problem is just that the Binding doesn't work and I'm not sure why? The VS output doesn't give me any clues.

Anyway, here's a code sample of the XAML:

<Window x:Class="WpfTestApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
    <Grid>
        <TabControl>
            <TabItem Header="tabItem1" />
            <TabItem Header="Hide me!" Visibility="{Binding ShowTab, Converter={StaticResource BoolToVis}}" />
        </TabControl>
    </Grid>
</Window>

And here's the .cs

    public bool ShowTab { get; set; }

    public MainWindow()
    {
        ShowTab = false;
        InitializeComponent();
    }

What am I missing? is there supposed to be some kind of DataContext connection somewhere? or is the code some kind of static resource? And why doesn't I get any clue from VisualStudio?

Upvotes: 1

Views: 120

Answers (1)

Sisyphe
Sisyphe

Reputation: 4682

Add DataContext = this; to your MainWindow constructor

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ShowTab = false;
    }

Please notice that your UI will not receive any notification if you modify ShowTab.

Upvotes: 2

Related Questions