5

次の簡単なコンバーターで値にバインドしているウィンドウに TextBox があります。

public class TestConverter : MarkupExtension, IValueConverter {
    public override object ProvideValue(IServiceProvider serviceProvider) {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        return "x";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        return "y";
    }
}

バインディング自体は次のように明示されています。

Binding bnd = new Binding(nm); // 'nm' is a string with the binding path which is just
                               // a property name of the future source object
bnd.Converter = new TestConverter();
bnd.Mode = BindingMode.OneWayToSource;
oj.Fe.SetBinding(TextBox.TextProperty, bnd); // <--- Exception occurs here

コンバーターを削除するか、モードを TwoWay に設定しても、例外は発生しません。それ以外の場合に例外が発生するのはなぜですか? また、問題を解決または少なくとも回避するにはどうすればよいですか?

編集:例外が発生しないようにバインドする前に、このシナリオではデータ コンテキストを提供する必要があるようです。なぜそうなのですか?

4

2 に答える 2

0

あなたはこれができますか?Binding のコンストラクターは文字列パスを受け入れ、文字列フィールドを渡していると思います。したがって、コンパイラは正常に動作しますが、WPF エンジンは混乱します。繰り返しますが、nm は Target TextBox から更新するソース プロパティをバインドしていると想定しています。

Binding bnd = new Binding("nm");

私はこのコードを書きましたが、うまくいきました。

<Grid>
        <TextBox Name="fe"></TextBox>
    </Grid>
// set datacontext
Binding bnd = new Binding("nm");
bnd.Converter = new TestConverter();
bnd.Mode = BindingMode.OneWayToSource;
fe.SetBinding(TextBox.TextProperty, bnd);
fe.Text = "Hi";

        public string nm 
        { 
            get
            {
                return _nm;
            }

            set
            {
                _nm = value;
            }
        }
于 2013-04-19T14:47:21.170 に答える