开发者

How to create databinding over two xaml files?

I am trying to come to a working understanding of how databinding works, but even after several tutorials I only have a basic understanding of how databinding works. Thus this question might seem fundamental to those more familiar with silverlight. Even if it is trivial, please point me to some tutorial that deals with this problem. All that I could find simply solved this via adding the data binding on a parent page.xaml (that i must not use in my case).

For the sake of this example let us开发者_StackOverflow社区 assume, that we have 5 files:

starter.cs
button1.xaml + codeBehind
button2.xaml + codeBehind

The two buttons are generated in code in the starter(.cs) file, and then added to some MapLayer

button1 my_button1 = new button1();   
button2 my_button1 = new button2();

someLayer.Children.Add(my_button1);
someLayer.Children.Add(my_button2);     

My aim is to connect the two buttons, so that they always display the same "text" (i.e. my_button1.content==my_button2.content = true;). Thus when something changes my_button1.content this change should be propagated to the other button (two way binding).

At the moment my button1.xaml looks like this:

<Grid x:Name="LayoutRoot">
<Button x:Name="x_button1" Margin="0,0,0,0" Content="{Binding ElementName=x_button2, Path=Content}" ClickMode="Press" Click="button1_Click"/>
</Grid>

But everthing that i get out of that is a button with no content at all, it is just blank as the binding silently fails. How could I create the databinding in the context I described? Preferably in code and not XAML ;)

Thanks in advance


The chunk of documentation you need to read is this: XAML Namescopes

Your button1 xaml has a binding looking for an element with the name "x_button2". However in a real application there can be many controls which in turn have nested controls. All of these controls have all manner of UI elements some of which may have names.

It would be impossible to get anything done if all names throughout the entire application had be unique. Yet that would need to be true if it were for your button1 to be able to hunt down the existence of another control somewhere in the visual tree outside of that which it actually knows (its own xaml).

Hence each loaded Xaml document exists in its own "namescope" and the search for other elements with other names is limited to that "namescope".

The are various solutions to this problem depending on what you real requirements are as opposed to the simplified problem in your question.

Typically you give each of your controls a DependencyProperty to which the inner button Content property binds. In "MapLayer" as call it, could then bind the propert on one of your button controls to the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜