How to bind to stackpanel children?
I define a stackpanel with 4 TextBlock inside it and I define some object that holds 4 strings as properties.
class a
{
pub开发者_开发知识库lic string str1;
public string str2;
public string str3;
public string str4;
}
<StackPanel>
<TextBlock x:Name="txt1" />
<TextBlock x:Name="txt2" />
<TextBlock x:Name="txt3" />
<TextBlock x:Name="txt4" />
</StackPanel>
I want to define a binding between the object instance of class a and the stackpanel TextBlock.Text
How can i do it ?
To bind to your str1-4 they have to be get/set Properties at a minimum (and notify properties if they will change after the view is connected to an instance of class a).
class a
{
public string str1 { get; set; }
public string str2 { get; set; }
public string str3 { get; set; }
public string str4 { get; set; }
}
<StackPanel>
<TextBlock x:Name="txt1" Text={Binding str1} />
<TextBlock x:Name="txt2" Text={Binding str2} />
<TextBlock x:Name="txt3" Text={Binding str3} />
<TextBlock x:Name="txt4" Text={Binding str4} />
</StackPanel>
I do not know where your class a exists, or if you are using MVVM (I am guessing not), but at a minimum in the constructor of the view you need to set the DataContext of the view (or just the stack panel) to your instance of "a".
e.g.
public MyView()
{
InitializeComponent();
this.DataContext = myaInstance;
}
or if you want to target the StackPanel only then name the StackPanel and set its DataContext:
<StackPanel x:Name="MyStackPanel">
public MyView()
{
InitializeComponent();
this.MyStackPanel.DataContext = myaInstance;
}
精彩评论