Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用WPF进行数据绑定_C#_Wpf_Data Binding - Fatal编程技术网

C# 使用WPF进行数据绑定

C# 使用WPF进行数据绑定,c#,wpf,data-binding,C#,Wpf,Data Binding,我想把一个按钮的宽度绑定到某个文本框的文本值,尽管我希望总是有一个按钮的宽度是文本框上所写宽度的两倍。这是: textBox1.Text = 10 将设置 button1.Width = 20 我只能通过ValueConverters执行此操作,还是有其他方法 感谢不是简单赋值的绑定,这就是值转换器的用途。 (没有其他方法可以做到。)使用IValueConverter是一个简单的解决方案,但如果您不想这样做,则可以尝试使用单个变量绑定textbox1和button1。例如,假设您创建了两个控

我想把一个按钮的宽度绑定到某个文本框的文本值,尽管我希望总是有一个按钮的宽度是文本框上所写宽度的两倍。这是:

textBox1.Text = 10
将设置

button1.Width = 20
我只能通过ValueConverters执行此操作,还是有其他方法


感谢不是简单赋值的绑定,这就是值转换器的用途。
(没有其他方法可以做到。)

使用IValueConverter是一个简单的解决方案,但如果您不想这样做,则可以尝试使用单个变量绑定textbox1和button1。例如,假设您创建了两个控件,如下图所示,并绑定到一个名为ButtonText的变量中。为简单起见,将修改按钮的内容,而不是按钮的宽度

在xaml中:

<TextBox Text="{Binding ButtonText, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="{Binding ButtonText, Mode=OneWay}"/>
不幸的是,此解决方案在.NET4.0中不起作用,因为.NET4.0处理OneWayToSource的方式,如本文所述。基本上,问题在于,文本框在被文本框设置后,将使用ButtonText的值更新文本框,尽管其模式配置为“OneWayToSource”。此解决方案适用于.NET3.5

为了解决.NET 4.0中的单向资源问题,您可以使用BlockingConverter(IValueConverter类型)来分离每次使用资源的时间,并设置x:Shared=“False”,,如本文所述。同样,您正在使用IValueConverter,但至少您没有使用它来修改值

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;