0

I have a FrameworkElementFactory works like a textbox created in the code, so there is no xaml code, and also I set this textbox with data binding in code. Now I want to update this textbox databinding by Enter key pressed. I have read one way for attached behavior in this Link, but it seems working with xaml code. Is there any way to set attached behavior in code behind?

ListBox DDF_List = new ListBox();

FrameworkElementFactory Editable_TextBox = new FrameworkElementFactory(typeof(TextBox));
Binding text_binding = new Binding("Value");
Editable_TextBox.SetBinding(TextBox.TextProperty, text_binding);

DataTemplate Text_Layout = new DataTemplate();
Text_Layout.VisualTree = Editable_TextBox;
DDF_List.ItemTemplate = Text_Layout;
Sam Xia
  • 171
  • 11

1 Answers1

0

You should almost certainly be doing this with a DataTemplate in XAML. What you've got is a prefect case for doing everything in XAML. But if you're committed to doing it the hard way, here's how.

With your FrameworkElementFactory, you can set it like any other dependency property on a FrameworkElementFactory:

Editable_TextBox.SetValue(
    InputBindingsManager.UpdatePropertySourceWhenEnterPressedProperty, 
    TextBox.TextProperty);

More generally, here's now to apply that attached property to a TextBox in C#, where itemNameTextBox is the TextBox:

InputBindingsManager.SetUpdatePropertySourceWhenEnterPressed(itemNameTextBox, 
    TextBox.TextProperty);

With attached properties, this C#:

var itemNameTextBox = new TextBox { Name = "itemNameTextBox" };

var binding = new Binding("ItemName")
{
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

itemNameTextBox.SetBinding(TextBox.TextProperty, binding);

//  This is the line you're asking for:
InputBindingsManager.SetUpdatePropertySourceWhenEnterPressed(itemNameTextBox, 
    TextBox.TextProperty);

Is an exact equivalent of this XAML:

<TextBox 
    Name="itemNameTextBox"
    Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}"
    b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"
    />