I'm new-ish to C# and wpf. I have a ChildWindow whose title gets set from outside the class. I need the title to be shortened with ellipsis on the end if it is too long. I accomplished by doing this (the code is shortened):
<Namespace:ChildWindow
x:Class="Namespace.MyClass">
<Namespace:ChildWindow.Title>
<TextBlock x:Name="_titleBlock" Width="300" TextTrimming="WordEllipsis"/>
</Namespace:ChildWindow.Title>
</Namespace:Childwindow>
However, I would like caller of this class to be able to set ChildWindow.Title = "Something long"
rather than ChildWindow._titleBlock = "Something long"
because I think that it makes more sense. Is it possible to do this through events somehow?
What you really want to do is use the MVVM pattern to split your logic out from your view. That way you can pass your ViewModel to the thing manipulating the child window instead of the child window itself.
For example, a basic ViewModel for the child window could be:
public class ChildWindowViewModel: INotifyPropertyChanged {
private string _title;
public string Title{
get { return _title; }
set{if (value != _title){
_title = value;
OnPropertyChanged("Title");
}}
}
private void OnPropertyChanged(string propertyName){
var handle = PropertyChanged;
if (handle != null){
handle(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
You then set the DataContext to the viewmodel when you create the child window like this:
//Creating the child window
ChildWindow child = new ChildWindow();
ChildWindowViewModel childViewModel = new ChildWindowViewModel();
child.DataContext = childViewModel;
//do stuff with child...
and hook the child windows Title up to the ViewModel in the Xaml like this:
<Namespace:ChildWindow
x:Class="Namespace.MyClass">
<Namespace:ChildWindow.Title>
<TextBlock Width="300" TextTrimming="WordEllipsis" Text="{Binding Path=Title}/>
</Namespace:ChildWindow.Title>
</Namespace:Childwindow>
Then when you want to change the title you can use
childViewModel.Title = "A Very Long Title That Will Be Cut Short In Its Prime";
Setting the title on the ViewModel will trigger the PropertyChanged event which will cause the Xaml view to update itself with the newly set value. This might seem like a VERY long winded way of doing things but if you think about what this allows you to do for a few minutes you'll see some huge benefits. The binding goes way beyond simple title texts...
Hopefully that will all work as is but I'm doing it from memory so sorry for any mistakes...