My WPF binding is not working because my viewmodel has overwritten Equals and GetHashCode. If i comment it out (region Object-Stuff), everything works fine.
Further info about my reasons: All my viewmodels have an Id. I load data with Id=1 and set the datacontext. Later i reload the data (same id, but other properties can have changed), i reset the datacontext and nothing happens (DataContextChanged-event is raised).
Has anybody an idea how to refresh the datacontext? (by the way, set it to null and then to my new viewmodel is not an solution because the regulation is that a views datacontext is never null). Here is some small demo code to reproduce this. Window.xaml:
<Grid>
<Button Content="Button1" HorizontalAlignment="Left" Margin="565,84,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="206,173,0,0" TextWrapping="Wrap" Text="{Binding Text}" VerticalAlignment="Top" Width="120"/>
<Button Content="Button2" HorizontalAlignment="Left" Margin="565,138,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
<Button Content="Button3" HorizontalAlignment="Left" Margin="565,191,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_2"/>
</Grid>
Window.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
ViewModel vm = new ViewModel { Id = 1, Text = "Button1" };
DataContext = vm;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ViewModel vm = new ViewModel { Id = 1, Text = "Button2" };
DataContext = vm;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ViewModel vm = new ViewModel { Id = 1, Text = "Button3" };
DataContext = vm;
}
ViewModel:
class ViewModel
{
public int Id { get; set; }
public string Text { get; set; }
#region Object-Stuff
public override int GetHashCode()
{
return Id.GetHashCode();
}
public override bool Equals(object obj)
{
ViewModel other = obj as ViewModel;
if ((object)other == null)
{
return false;
}
return Id == other.Id;
}
public virtual bool Equals(ViewModel other)
{
if ((object)other == null)
{
return false;
}
return Id == other.Id;
}
#endregion
}