Reputation: 52
I'm trying to bind the Content
property of a simple label to a property of an other class. I already tried various approaches but it didn't work yet.
Here is the property in the source class (MainWindow.xaml.cs):
public String FileTitle
{
get
{
return this.GetValue(FiletitleProperty) as string;
}
set
{
this.SetValue(FiletitleProperty, value);
}
}
public DependencyProperty FiletitleProperty;
public MainWindow()
{
FiletitleProperty = DependencyProperty.Register("FileTitle", typeof(String), typeof(MainWindow));
...
}
In my target class i have an object of the source class called CallbackObject
(the naming is not really suitable)
Here is my xaml code of the binding:
<Label x:Name="lblFiletitle" Content="{Binding Source=CallbackObject, Path=FileTitle}" Margin="10,213,10,0" Height="35" VerticalAlignment="Top" FontSize="16" Padding="0,5,5,5" />
Is it even possible to do it that way or do i have to make it more complicated and inelegant?
Upvotes: 0
Views: 84
Reputation: 1091
If CallbackObject
is in code behind try:
<Label Content="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType=UserControl,Mode=FindAncestor}, Path=CallbackObject.FileTitle}" />
Upvotes: 1
Reputation: 1532
If your label is placed inside a UserControl or a Page, you cannot bind directly to a property in another object (be it a Window or whatever) without creating an instance or a reference of that object in your -let's say- UserControl. The parent element in the hierarchy (the topmost element in your XAML) defines the DataContext scope of the child elements. They only can bind to things within that scope.
There are some workarounds to this:
You can call with relative ease a static property and then a binding like "{x:Static local:StaticClass.StaticProperty}".
You can create an instance of the referred object in your UserControl (either in XAML or in code behind) and set the DataContext of the UserControl to itself. The referred object must be exposed in a public property with public get and set (if needed) accesors. You don't need dependecy properties if you implement INotifyPropertyChanged (whichever you prefer).
If you want to get data from a different Window or from a different ViewModel, there are many ways to do it. It's too long (and too "available") to post here, a quick search will give you lots of results.
In your case, I guess that you have only one MainWindow in your app, so maybe you could create a static property to return the current MainWindow instance, and then bind to any of its properties from anywhere.
This code inside your MainWindow.xaml.cs
private static MainWindow_instance;
public static MainWindow Instance
{
get
{
if (_instance == null)
_instance = new MainWindow();
else
_instance = this;
return _instance;
}
}
Caveat: this works for me in certain situations, but I never used it for the MainWindow and I'm not sure this is the best of practices. It works, though.
Hope this helps, regards!
Upvotes: 0