I have created a custom control but have some weird issues with data binding. The control has a DependencyProperty called Status that requires an object of type StatusBlockData. If I create a StatusBlockData object, use it directly as DataContext for my window and bind my control with Status={Binding .} the binding works.
But when I create the object as property in my view public StatusBlockData Status { get; set; }, use the view as DataContext for the window and change the binding of my control to Status="{Binding Status}", it does not work anymore.
I am majorly confused. In both cases I bind to a StatusBlockData object, right? Here is some code. I assume that the style for the control is not important because in the first case the binding works properly.
This is my view (the Header property is only for testing):
public ViewMainWindow()
{
Status = new StatusBlockData(5);
Status.SetStatus("does not work", StatusIcon.Information);
Header = "Binding works";
}
public string Header { get; set; }
public StatusBlockData Status { get; set; }
}
Using the view does not work:
public MainWindow()
{
InitializeComponent();
ViewMainWindow view = new ViewMainWindow();
this.DataContext = view;
view.Status.SetStatus("this is not displayed", StatusIcon.Success);
}
XAML looks like this (again - Header is only for testing):
<GrassoftUtils:StatusBlock Status="{Binding Status}" Background="Red" Width="159"/>
<TextBlock Text="{Binding Header}" HorizontalAlignment="Left" Margin="168,101,0,0" VerticalAlignment="Top" />
But without view, it works:
public MainWindow()
{
InitializeComponent();
StatusBlockData Status = new StatusBlockData(5);
this.DataContext = Status;
Status.SetStatus("this works", StatusIcon.Information);
}
And the binding (and the textblock is of course empty):
<GrassoftUtils:StatusBlock Status="{Binding .}" Background="Red" Width="159"/>
<TextBlock Text="{Binding Header}" HorizontalAlignment="Left" Margin="168,101,0,0" VerticalAlignment="Top" />
Another weird thing I have just realized: The binding of Status="{Binding .}" always works, regardless of what comes behind the word Binding. I'd expect it to fail. Is that part of the problem?
Just to be save, this is the style for the control:
<Style TargetType="{x:Type Controls:StatusBlock}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Controls:StatusBlock}">
<Grid Height="24" Background="{TemplateBinding Background}" Visibility="{Binding Path=StatusVisible, Converter={StaticResource VisibilityConverter}}">
<Image Height="24" Width="24" Source="{Binding StatusIcon, Converter={StaticResource StatusIconConverter}}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBlock Margin="28,0,0,0" Text="{Binding StatusText}" HorizontalAlignment="Left" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
StatusBlockDataclass fully implements INotifyPropertyChanged