0

How do i bind two TextBox objects to a System.Windows.Size struct? The binding only has to work in this direction:

(textBox1.Text + textBox2.Text) => (Size)

After a user inserts the width and height in the TextBoxes on the UI the Size object should be created.

XAML:

<TextBox Name="textBox_Width" Text="{Binding ???}" />
<TextBox Name="textBox_Height" Text="{Binding ???}" />

C#:

private Size size
{
  get;
  set;
}

Is there an easy way to do this?

Edit: Size is a struct! Therefore "someObject.Size.Width = 123" does not work. I need to call the Size-Constructor and set someObject.Size = newSize

2 Answers 2

3

Could you not just expose 2 properties - width and height from your model, along with a size property. The width and height would appear in your {Binding} expressions, and then when you want to get the size property, it initialises based on these two fields.

Eg, your model might be something like;

public class MyModel
{
    public int Width{ get; set; }
    public int Height{ get; set; }

    public Size Size{ get{ return new Size( Width, Height ); }}
};

Hope this helps.

Tony

Sign up to request clarification or add additional context in comments.

Comments

0

Window1.xaml.cs:

public partial class Window1 : Window
{
    public static readonly DependencyProperty SizeProperty = DependencyProperty.Register("Size",
        typeof(Size),
        typeof(Window1));

    public Size Size
    {
        get { return (Size)GetValue(SizeProperty); }
        set { SetValue(SizeProperty, value); }
    }

    public Window1()
    {
        InitializeComponent();
        DataContext = this;
        _button.Click += new RoutedEventHandler(_button_Click);
    }

    void _button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Size.ToString());
    }
}

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <TextBox Text="{Binding Size.Width}"/>
        <TextBox Text="{Binding Size.Height}"/>
        <Button x:Name="_button">Show Size</Button>
    </StackPanel>
</Window>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.