Reputation: 105217
I want to bind a button's width to some textbox's text value, although I want to always have a button width's that's twice what is written on the textbox. This is:
textBox1.Text = 10
will set
button1.Width = 20
Can I only do this through ValueConverters or is there other way to do it?
Thanks
Upvotes: 2
Views: 166
Reputation: 218
Using IValueConverter is the easy solution but if you do not wish to do so, then you can try binding textbox1 and button1 with a single variable. For example, let say you have created two controls as seen in below and have binded into a single variable called ButtonText. For simplicity, Content of the button will be modified instead of Width of the button.
In xaml:
<TextBox Text="{Binding ButtonText, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="{Binding ButtonText, Mode=OneWay}"/>
In ViewModel:
public string ButtonText
{
get { return _buttonText; }
set
{
int result;
if (int.TryParse(value, out result))
_buttonText = (result * 2).ToString();
else
_buttonText = value;
OnPropertyChanged("ButtonText");
}
}
private string _buttonText;
Unfortunately, this solution does not work in .NET 4.0 because the way .NET 4.0 handles OneWayToSource, as stated in this article. Basically, the issue is that the Textbox will be updated with the value from ButtonText after it is set by the Textbox although its Mode was configured as "OneWayToSource". This solution will work for .NET 3.5.
To get around this OneWayToSource issue in .NET 4.0, you can use BlockingConverter (type of IValueConverter) to separate each time that the resource is used and set x:Shared="False", as stated in this article. Then again, you are using the IValueConverter but at least you are not using it to modify the value.
Upvotes: 2
Reputation: 18118
Bindings that are not simple assignments, that is what value converters are for. (No other way to do it.)
Upvotes: 1