ek32 ek32 - 2 months ago 10
C# Question

Wpf Textbox UpdateSourceTrigger doesn't update the source

I have a simple Window with a TextBox

XAML

<Window x:Class="Configurator.ConfiguratorWindow"
x:Name="ConfigWindow" DataContext="{Binding RelativeSource={RelativeSource Self}}">

<TextBox x:Name="DescriptionTextBox" Text="{Binding Path=Description, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>

</Window>


in the code behind

public partial class ConfiguratorWindow : Window
{
public ConfiguratorWindow()
{
InitializeComponent();
}

private static DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(string), typeof(ConfiguratorWindow), new PropertyMetadata());

public string Description
{
get { return GetValue(DescriptionProperty).ToString(); }
set {
SetValue(DescriptionProperty, value);
_actual_monitor.Description = value;
}
}
}


the graphic is updating right, but when i change the text in the textbox and lose focus it doesn't update the source property.

What is wrong?

Answer

Try this

<Window x:Class="Configurator.ConfiguratorWindow"
         xmlns:myWindow="clr-namespace:YourNamespace"
x:Name="ConfigWindow" DataContext="{Binding RelativeSource={RelativeSource Self}}">

<TextBox x:Name="DescriptionTextBox" Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type myWindow}}, Path=Description, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>

public partial class ConfiguratorWindow : Window
{
public ConfiguratorWindow()
    {
        InitializeComponent();
    }

private static DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(string), typeof(ConfiguratorWindow), new PropertyMetadata(null, CallBack);

 private static void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var foo = d as ConfiguratorWindow ;
       all you need to do, you can do here
    }

public string Description
    {
        get { return GetValue(DescriptionProperty).ToString(); }
        set { SetValue(DescriptionProperty, value);}
    }
}

But it would be much easier to just have a View Model and bind to property there.