9

私の UserControl では、XAML に次のコードがあります。

<TextBlock Grid.Row="2" Text="{Binding Path=StartTime,
                               RelativeSource={RelativeSource Mode=FindAncestor,
                                AncestorLevel=1, AncestorType=Window}}" />

これは、親ウィンドウからプロパティの値を取得するだけで、うまく機能します。

コードビハインドでこれを行うにはどうすればよいですか?

Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
                                      typeof(Window), 1);
b.Path = "StartTime";

myProperty = b.value;// obviously there is no b.value but this
                     // is what I'm trying to achieve.

//BindingOperations.SetBinding(StartTime, StartTimeProperty, b);
//This does not work sadly, it can't convert string to DependancyObject
4

2 に答える 2

18

x:Nameあなたの TextBlock に与える-

次に、このようなコードビハインドでそれを行うことができます-

Binding b = new Binding("StartTime");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor,
                                         typeof(Window), 1);
textBlock.SetBinding(TextBlock.TextProperty, b);
于 2013-11-05T17:09:05.410 に答える
10

試してみてくださいBindingOperations.SetBinding。これは次のように機能するはずです。

BindingOperations.SetBinding(this, myProperty, b);

(それが であり、DependencyPropertythisであるDependencyObjectと仮定します。myProperty

于 2013-11-05T16:19:34.857 に答える