I have the object MyObject Object in the class MainClass.xaml.
I want to pass this object to a ViewModel class of a nested user control called SubSubUserControl through a SubUserControl.
Here is the code in MainClass.xaml:
<UserControl x:Class="Test.SubUserControl"
d:DataContext="{d:DesignInstance d:Type=local:SubUserControlViewModel}">
<Grid>
<local:SubSubUserControl Object="{Binding Object, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SubUserControl}}}"/>
</Grid>
</UserControl>
In SubUserControl I have a classical DependencyProperty in order to pass Object to it.
public static readonly DependencyProperty ObjectProperty = DependencyProperty.Register(nameof(Object), typeof(Object), typeof(SubUserControl));
public Object Object
{
get => (Object)GetValue(ObjectProperty);
set => SetValue(ObjectProperty, value);
}
protected override void OnInitialized(EventArgs e)
{
InitializeComponent();
DataContext = new SubUserControlViewModel(Object);
base.OnInitialized(e);
}
SubUserControl is only a "bridge", the object Object is needed in SubSubUserControl.
I pass to it with a binding (changing Datacontex beacause the standard DataContext for SubUserControl is his ViewModel).
<local:SubSubUserControl Object="{Binding Object, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
and SubSubUserControl has the classical DependencyProperty.
SubSubUserControl has a ViewModel as DataContext and I'd like to pass that object to it.
I try with
public static readonly DependencyProperty ObjectProperty = DependencyProperty.Register(nameof(Object), typeof(Object), typeof(SubSubUserControl));
public Object Object
{
get => (Object)GetValue(ObjectProperty);
set => SetValue(ObjectProperty, value);
}
protected override void OnInitialized(EventArgs e)
{
InitializeComponent();
DataContext = new SubSubUserControlViewModel(Object);
base.OnInitialized(e);
}
but Object is null.
The same code in SubUserControl works.
Is there a way to pass an object using binding to a ViewModel class that belongs to a nested UserControl?
I saw a lot of similar questions but noone works with my specific case...
EDIT
The class Object is instanced code-behind in MainClass.xaml.cs. In order to pass it I set the DataContext of MainClass to Self.
public MyObject Object { get; set; } = new MyObject();
Here is how I set DataContext in MainClass.xaml
<Window x:Class="Test.MainWindow"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<local:SubUserControl Object="{Binding Object}"/>
</Grid>
</Window>
Setting the DataContext to the entire Window avoid me to write something like ElementName or Relative Source.
P.s. Resharper do not warn me about any DataContext, each instance is seen correctly.
I don't know the method OnInitialized, but from the documentation :
Raises the Initialized event.
And the event Initialized :
Whether you choose to handle Loaded or Initialized depends on your requirements. If you do not need to read element properties, intend to reset properties, and do not need any layout information, Initialized might be the better event to act upon. If you need all properties of the element to be available, and you will be setting properties that are likely to reset the layout, Loaded might be the better event to act upon.
I think the binding work, but you try to read the value in OnInitialized that is called before the binding is resolved.
As suggested in the documentation, maybe you can use the event Loaded like :
public partial class SubSubUserControl : UserControl
{
public SubSubUserControl()
{
InitializeComponent();
Loaded += SubSubControl_Loaded;
}
private void SubSubControl_Loaded(object sender, RoutedEventArgs e)
{
DataContext = new SubSubViewModel(TargetFoo);
}
}
A alternative is to update the data context when the dependency property is modified :
public partial class SubSubUserControl : UserControl
{
public static readonly DependencyProperty ObjectProperty = DependencyProperty.Register(
"Object", typeof(MyObject),
typeof(SubSubUserControl),
new PropertyMetadata(OnObjectChanged)
);
private static void OnObjectChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if(sender is SubSubControl ssc)
{
ssc.DataContext = new SubSubViewModel((MyObject)e.NewValue);
}
}
}
EDIT from exchanges in comments.
It looks like you have a binding problem too. I suspect that a other element of type UserControl encapsulate the SubSubUserControl, like :
MainClass
SubUserControl
OtherUserControl
SubSubUserControl
In this case, the binding will use OtherUserControl as source (and not the expected SubUserControl).
In this case, you can specify in the binding the source's type is SubUserControl to avoid a other element of type UserControl is selected :
<local:SubSubUserControl Object="{Binding BridgeFoo, RelativeSource={RelativeSource AncestorType={x:Type local:SubUserControl}}}" />
A alternative is to use Binding.ElementName instead of Binding.RelativeSource :
<UserControl x:Class="ProjectNamespace.SubUserControl"
...
xmlns:local="clr-namespace:ProjectNamespace"
Name="Sub">
<local:SubSubUserControl Object="{Binding Object, ElementName=Sub}" />
</UserControl>
I prefer this, because I never remember the RelativeSource syntax.
Related
I created UserControl with viewmodel. It has DependencyProperty which only works if the value is passed directly. If the value is passed through the binding, it no longer works.
Here is the view code:
This is a closed element not associated with any other. All listed items belong to him. This is a code shortening, I am not going to present whole, immeasurable structures.
View
public partial class SomeView : UserControl
{
public SomeView()
{
InitializeComponent();
SetBinding(ActiveProperty, new Binding(nameof(SomeViewModel.Active)) { Mode = BindingMode.OneWayToSource });
}
#region ActiveProperty
public static readonly DependencyProperty ActiveProperty = DependencyProperty.Register(nameof(Active), typeof(bool), typeof(VNCBoxView));
public bool Active
{
get { return (bool)GetValue(ActiveProperty); }
set { SetValue(ActiveProperty, value); }
}
}
VievModel
public class SomeViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool active;
public bool Active
{
get { return active; }
set
{
active = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Active)));
}
}
}
UserControl
<UserControl ...>
<UserControl.DataContext>
<viewModels:SomeViewModel />
</UserControl.DataContext>
<Grid>
<TextBlock Text="{Binding Active}" />
</Grid>
</UserControl>
===================================================
When working with a ready component, which is an individual, separate entity, the problem occurs depending on how it is used.
I remind you that the elements used in the view in question are a closed whole that does not connect with the element in which it is used. It is the transfer of value that is the matter of the problem.
This is working usage:
<local:SomeView Active="True" />
In viewmodel, the setter is invoked twice, once with false and then with true.
If the value comes from binding, it doesn't work:
<local:SomeView Active="{Binding SomeParentProperty}" />
In viewmodel, setter is only called once with the value false.
Setters in a view are never called, in both cases.
Please help
There is no IsConnected property in the SomeViewModel instance in the current DataContext of the UserControl, hence the Binding
<local:SomeView Active="{Binding IsConnected}" />
won't work. It tries to resolve the PropertyPath against the current DataContext, unless you explicitly specify its Source, RelativeSource or ElementName.
This is the exact reason why UserControls should never explicitly set their own DataContext, and hence never have something like an own, private view model.
The elements in the UserControl's XAML would not bind to properties of such a private view model object, but directly to the properties of the UserControl, for example like
<TextBlock Text="{Binding Active,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
When you set the DataContext explicitly in the UserControl like this:
<UserControl.DataContext>
<viewModels:SomeViewModel />
</UserControl.DataContext>
...you can no longer bind to SomeView's DataContext in the consuming view like this:
<local:SomeView Active="{Binding IsConnected}" />
...because SomeViewModel doesn't have any IsConnected property.
You should avoid setting the DataContext explicitly and let the UserControl inherit its DataContext from its parent element. You can still bind to the dependency property of the UserControl itself using a RelativeSource or an ElementName:
<UserControl ...>
<Grid>
<TextBlock Text="{Binding Active, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Grid>
</UserControl>
Besides, SomeViewModel seems superfluous in your example since the UserControl already has an Active property.
I found a lot of examples on how to bind the IsChecked property of a WPF checkbox to a boolean property, if both belong to the same Window class. I want to do a different thing:
I have the main window (excerpt):
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private readonly SoundFx _soundFx = new SoundFx();
private void _StartNewGame()
{
_soundFx.GameStarted();
}
}
Then I have the SoundFx class (excerpt):
public class SoundFx : DependencyObject
{
public void GameStarted()
{
if (Enabled)
{
_PlayGameStartedSound();
}
}
public bool Enabled
{
get { return (bool) GetValue(EnabledProperty); }
set { SetValue(EnabledProperty, value); }
}
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.Register("Enabled", typeof(bool),
typeof(SoundFx), new UIPropertyMetadata(false));
}
And I have the XAML (excerpt):
<Grid>
<CheckBox IsChecked="{Binding ElementName=_soundFx, Path=Enabled}" x:Name="checkBoxSoundFx" Content="Sound FX" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom"/>
</Grid>
To be honest, I'm new to WPF and don't know exactly what I'm doing. What I'm trying to achieve is that the value of _soundFx.Enabled be changed when the user clicks on the checkBoxSoundFx element, without using any event handlers like Checked or Unchecked. This should be possible with data binding, shouldn't it?
First you need to create
public SoundFx _soundFx { get; set; }
as public property, because you cannot bind to private field
public MainWindow()
{
InitializeComponent();
_soundFx = new SoundFx();
}
And from xaml you need to bind like:
<CheckBox IsChecked=
"{Binding RelativeSource=
{RelativeSource Mode=FindAncestor,AncestorType=Window},
Path=_soundFx.Enabled}"}"
x:Name="checkBoxSoundFx"
Content="Sound FX"
HorizontalAlignment="Right"
Margin="0,0,10,10"
VerticalAlignment="Bottom"/>
You were close, you need a property to bind to and you need to set the DataContext if you didn't do it:
public partial class MainWindow
{
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
}
private readonly SoundFx _soundFx = new SoundFx();
public SoundFx {get {return _soundFx;}}
private void _StartNewGame()
{
_soundFx.GameStarted();
}
}
You then need to bind to this property (and set the mode to OneWayToSource if you only need to set the property, never update the CheckBox according to the property value):
<Grid>
<CheckBox IsChecked="{Binding Path=SoundFx.Enabled, Mode=OneWayToSource}" x:Name="checkBoxSoundFx" Content="Sound FX" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom"/>
</Grid>
By the way I'm not sure why you SoundFx is a DependencyObject and why your Enabled property is a DependencyProperty. A simple property would work aswell in this particular example.
DependencyProperties are useful when you want to set them in a Style or animate them with a Storyboard for example, you don't seem to be in this case. I think SoundFx should inherit DependencyObject and Enabled should be a simple property (This is an opinion I make knowing very little about your project though).
As I've managed to grow more experienced in WPF in the meantime, I would now say that my question itself was wrong. In order to avoid confusion in binding and unnecessary dependencies between view and model, I would now always prefer MVVM for cases like this.
Example: https://codereview.stackexchange.com/questions/124361/mvvm-am-i-doing-it-right
I have two user-controls: a LocationTreeView, and a LocationPicker. The LocationTreeView organizes Locations into a tree structure. Because of the number of locations involved, only parts of the tree are loaded at once (one level at a time as items are expanded).
The LocationPicker is little more than a textblock with a button that opens a modal window with a LocationTreeView on it.
When I bind my LocationPicker's "SelectedLocation" property to my Viewmodel, it works fine. When I bind my LocationTreeView to the viewmodel, the binding doesn't seem to have any effect at all. When I bind my LocationTreeView to a "dummy" LocationPicker (which is bound to my viewmodel) it works.
How can I get my LocationTreeView to bind to my viewmodel?
public partial class LocationTreeView: UserControl
{
public EventHandler LocationChanged;
...
public static readonly DependencyProperty SelectedLocationProperty =
DependencyProperty.Register("SelectedLocation",typeof(Location), typeof(LocationTreeView),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedLocationChanged));
...
public static void SelectedLocationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LocationTreeView sender = (d as LocationTreeView);
Location loc = e.NewValue as Location;
//Navigate the treeview to the selected location
sender.LoadLTreeViewPathToLocation(loc);
}
public Location SelectedLocation
{
get { return (Location)GetValue(SelectedLocationProperty); }
set
{
if (SelectedLocation != value)
{
SetValue(SelectedLocationProperty, value);
if (LocationChanged != null)
{
LocationChanged(this, EventArgs.Empty);
}
}
}
}
...
}
Binding on this control works fine when bound to another control, but not when bound to my viewmodel. I've set a breakpoint in the SelectedLocationChanged callback, it doesn't seem to get fired when I set the viewmodel property (which DOES implement INotifyPropertyChanged)
public partial class LocationPicker: UserControl
{
public static readonly DependencyProperty SelectedLocationProperty =
DependencyProperty.Register("SelectedLocation",typeof(Location), typeof(LocationPicker),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
...
public Location SelectedLocation
{
get { return (Location)GetValue(SelectedLocationProperty); }
set { SetValue(SelectedLocationProperty, value); }
}
...
private void Button_Click(object sender, RoutedEventArgs e)
{
// create a window with a locationtreeview on it. Set the treeview's
// selectedlocation property, open the window, wait for the window to close,
// set this.SelectedLoctation to the treeview's selected location.
}
}
I apologize for the leaving out so much code. My work enviroment prevents me from being able to copy/paste.
I've left out the code for the ViewModel. I am quite confident that it is not the issue.
Update:
The LocationTreeView has a ViewModel that is set in the xaml
<UserControl.DataContext>
<VM:LocationTreeViewViewModel />
</UserControl.DataContext>
The LocationPicker does not have a ViewModel.
On the window that I am using the controls, the xaml looks something like this
<Widow.DataContext>
<VM:TestWindowViewModel />
</Window.DataContext>
<Grid>
...
<UC:LocationPicker x:Name="picker" SelectedLocation="{Binding Location}" />
<!-- this does not work -->
<UC:LocationTreeView SelectedLocaiton="{Binding Location}" />
<!-- but this works --->
<UC:LocationTreeView SelectedLocaiton="{Binding SelectedLocation, ElementName=picker}" />
...
</Grid>
If you want to data bind from your view model to the LocationTreeView, then you should use the property in the view model to data bind to. If your view model had a property named SelectedLocationInViewModel in it, then you should use that to data bind to:
<UC:LocationTreeView SelectedLocation="{Binding SelectedLocationInViewModel}" />
I think that I see what your problem is now... you want to define some properties in the UserControl and data bind to them, but also data bind to properties from the view model that is set as the DataContext. You need to use a RelativeSource Binding to do that... just look at the Binding Paths in these examples:
To data bind to properties declared in a UserControl from within the UserControl:
<ItemsControl ItemsSource="{Binding PropertyName, RelativeSource={RelativeSource
AncestorType={x:Type YourPrefix:YourUserControl}}}" />
To data bind to properties declared in any object set as the DataContext:
<ItemsControl ItemsSource="{Binding PropertyName}" />
I like to create a UserControl with own Header Property.
public partial class SomeClass: UserControl, INotifyPropertyChanged
{
public SomeClass()
{
InitializeComponent();
}
private string header;
public string Header
{
get { return header; }
set
{
header = value;
OnPropertyChanged("Header");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
in UserContol xaml:
Label Name="lbHeader" Grid.Column="0" Content="{Binding Path=Header}"
If I set the value: AA2P.Header = "SomeHeeaderText"; than the label.Caption will not changed. How can I solve that problem?
In Windows xaml:
uc:SomeClass x:Name="AA2P"
If I give directly a value to label (lbHeader.Content = header;) instead of OnPropertyChanged("Header"); its work but, why it does not work with OnPropertyChanged?
I need to use DataContext for somethig else. I try to use dependency property but something is wrong.
public partial class tester : UserControl
{
public tester()
{
InitializeComponent();
}
public string Header
{
get { return (string)GetValue(MyDependencyProperty); }
set { SetValue(MyDependencyProperty, value); }
}
public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register("MyDependencyProperty", typeof(string), typeof(string));
}
<UserControl ... x:Name="mainControl">
<TextBlock Text="{Binding ElementName=mainControl, Path=MyDependencyProperty}"/>
</UserControl>
<Window ...>
<my:tester Header="SomeText" />
</Window>
It does not work. What I do wrong?
Thanks!
The easiest approach is to just the DataContext of your object. One way of doing that is directly in the constructor like this:
public SomeClass()
{
InitializeComponent();
DataContext = this;
}
Setting the DataContext will specify where new data should be fetched from. There are some great tips and information in the article called WPF Basic Data Binding FAQ. Read it to better understand what the DataContex can be used for. It is an essential component in WPF/C#.
Update due to update of the question.
To my understanding you should change the first argument of DependencyProperty.Register to the name of the property that you want to bind to, here "Header" as well as the second argument to the type of your class, here SomeClass. That would leave you with:
public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register("Header", typeof(SomeClass), typeof(string));
But i seldom use dependency properties so I am not positive that this is it, but its worth a try..
If you need the Data context for something else. You can also utilize the ElementName property in the Binding.
<UserControl
x:Class="MyControl.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="mainControl">
<TextBlock Text="Binding ElementName=mainControl, Path=MyDependencyProperty}"/>
</UserControl>
[Edit]
I should add something. Make the "Header" property a dependency property, this will make your live much easier. In UI Controls you should make property almost always a dependency property, every designer or user of your control will thank you.
The UserControl itself needs the DataContext of where it is used later. But the controls inside the UserControl need the UserControl as their DataContext, otherwise they also will inherit the DataContext from the later usage context. The trick is to set the DataContext of the UserControl's child to that of the UserControl, so it now can use the dependency properties of the UserControl.
<UserControl x:Class="MyControl.MyUserControl">
<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=UserControl,AncestorLevel=1}}">...</Grid>
</UserControl>
If you do this this way the children of the Grid can have simple {Binding dp's name} without additionally ElementName parameters.
I have some object that is instantiated in code behind, for instance, the XAML is called window.xaml and within the window.xaml.cs
protected Dictionary<string, myClass> myDictionary;
How can I bind this object to, for example, a list view, using only XAML markups?
Update:
(This is exactly I have in my test code):
<Window x:Class="QuizBee.Host.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding windowname}" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
</Grid>
</Window>
And in codebehind
public partial class Window1 : Window
{
public const string windowname = "ABCDEFG";
public Window1()
{
InitializeComponent();
}
}
Suppose the title should become "ABCDEFG" right? but it ends up showing nothing.
There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.
Window1.xaml
<Window x:Class="QuizBee.Host.Window1"
x:Name="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>
Window1.xaml.cs
public partial class Window1:Window
{
// the property must be public, and it must have a getter & setter
public Dictionary<string, myClass> myDictionary { get; set; }
public Window1()
{
// define the dictionary items in the constructor
// do the defining BEFORE the InitializeComponent();
myDictionary = new Dictionary<string, myClass>()
{
{"item 1", new myClass(1)},
{"item 2", new myClass(2)},
{"item 3", new myClass(3)},
{"item 4", new myClass(4)},
{"item 5", new myClass(5)},
};
InitializeComponent();
}
}
You can set the DataContext for your control, form, etc. like so:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Clarification:
The data context being set to the value above should be done at whatever element "owns" the code behind -- so for a Window, you should set it in the Window declaration.
I have your example working with this code:
<Window x:Class="MyClass"
Title="{Binding windowname}"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Height="470" Width="626">
The DataContext set at this level then is inherited by any element in the window (unless you explicitly change it for a child element), so after setting the DataContext for the Window you should be able to just do straight binding to CodeBehind properties from any control on the window.
While Guy's answer is correct (and probably fits 9 out of 10 cases), it's worth noting that if you are attempting to do this from a control that already has its DataContext set further up the stack, you'll resetting this when you set DataContext back to itself:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
This will of course then break your existing bindings.
If this is the case, you should set the RelativeSource on the control you are trying to bind, rather than its parent.
i.e. for binding to a UserControl's properties:
Binding Path=PropertyName,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}
Given how difficult it can be currently to see what's going on with data binding, it's worth bearing this in mind even if you find that setting RelativeSource={RelativeSource Self} currently works :)
Just a little more clarification: A property without 'get','set' won't be able to be bound
I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:
//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
public String My_Property { get; set; }
...
//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
...
public my_class() {
My_Property = "my-string-value";
InitializeComponent();
}
//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding My_Property}"/>
</Window>
In your code behind, set the window's DataContext to the dictionary. In your XAML, you can write:
<ListView ItemsSource="{Binding}" />
This will bind the ListView to the dictionary.
For more complex scenarios, this would be a subset of techniques behind the MVVM pattern.
One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.
In your XAML you should have something like this:
<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />
Define a converter:
public class RowIndexConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
var row = (IDictionary<string, object>) value;
var key = (string) parameter;
return row.Keys.Contains( key ) ? row[ key ] : null;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException( );
}
}
Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.
public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
private Dictionary<string, object> _data = new Dictionary<string, object>( );
public object Dummy // Provides a dummy property for the column to bind to
{
get
{
return this;
}
set
{
var o = value;
}
}
public object this[ string index ]
{
get
{
return _data[ index ];
}
set
{
_data[ index ] = value;
InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
}
}
}
In your .xaml file use this converter. First reference it:
<UserControl.Resources>
<ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>
Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use
<TextBlock Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">
Make your property "windowname" a DependencyProperty and keep the remaining same.
I was having this exact same problem but mine wasn't because I was setting a local variable... I was in a child window, and I needed to set a relative DataContext which I just added to the Window XAML.
<Window x:Class="Log4Net_Viewer.LogItemWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="LogItemWindow" Height="397" Width="572">
You can try x:Reference trick
<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>
That's my way to bind to code behind (see property DataTemplateSelector)
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataTemplateSelector = new MyDataTemplateSelector();
InitializeComponent();
// ... more initializations ...
}
public DataTemplateSelector DataTemplateSelector { get; }
// ... more code stuff ...
}
In XAML will referenced by RelativeSource via Ancestors up to containing Window, so I'm at my Window class and use the property via Path declaration:
<GridViewColumn Header="Value(s)"
CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>
Setting of property DataTemplateSelector before call InitializeComponent depends on missing implementation of IPropertyChanged or use of implementation with DependencyProperty so no communication run on change of property DataTemplateSelector.