我有一个包含3个字符串的类
e.g:
class abc
{
public string a, b, c;
public abc(string d, string e, string f)
{
a = d;
b = e;
c = f;
}
};
private void button1_Click(object sender, RoutedEventArgs e)
{
abc obj = new abc("abc1","abc2","abc3");
var MainPage1 = new MainPage();
MainPage1.DataContext = obj;
}
当我尝试绑定到文本块时,它不会绑定
<TextBlock Height="23" HorizontalAlignment="Left" Margin="201,66,0,0" Name="textBlock1" **Text="{Binding Path=a}"** VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="201,107,0,0" Name="textBlock2" **Text="{Binding Path=b}"** VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="201,156,0,0" Name="textBlock3" **Text="{Binding Path=c}"** VerticalAlignment="Top" />
我想我错过了什么,但需要帮助才能找到它。感谢
答案 0 :(得分:1)
您不允许绑定到字段,使其成为您的类的属性。
答案 1 :(得分:0)
From MSDN:数据绑定引擎支持任何公共语言运行时(CLR)对象的公共属性,子属性以及索引器。
因此使用属性而不是公共字段:
public class abc
{
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
public abc(string d, string e, string f)
{
a = d;
b = e;
c = f;
}
}
现在您可以将其设置为DataContext
,例如在MainPage的构造函数中:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
abc obj = new abc("abc1", "abc2", "abc3");
this.DataContext = obj;
}
}