I have a simple program containing a Dictionary with some values in it. At startup I populate the dictionary. But when I bind to the value nothing is displayed. what am I doing wrong?
My class:
class Constants
{
public static Dictionary<string, string> testDic;
public Constants()
{
testDic = new Dictionary<string, string>();
testDic.Add("KEY_Test1", "Test 1");
testDic.Add("KEY_Test2", "Test 2");
testDic.Add("KEY_Test3", "Test 3");
testDic.Add("KEY_Test4", "Test 4");
}
}
My main:
public MainWindow()
{
Constants con = new Constants();
InitializeComponent();
}
My XAML:
<Grid>
<TextBlock Text="{Binding Path=testDic[KEY_Test3]}"/>
</Grid>
Change your binding to following:
<TextBlock Text="{Binding Path=[KEY_Test3], Source={x:Static local:Constants.testDic}}"/>
Or If you want to do it using the get/set properties, then:
public class Constants
{
private Dictionary<string, string> testDic;
public Dictionary<string, string> TestDic
{
get { return testDic; }
set { testDic = value; }
}
public Constants()
{
TestDic = new Dictionary<string, string>();
TestDic.Add("KEY_Test1", "Test 1");
TestDic.Add("KEY_Test2", "Test 2");
TestDic.Add("KEY_Test3", "Test 3");
TestDic.Add("KEY_Test4", "Test 4");
}
}
public partial class MainWindow : Window
{
private Constants myConstants;
public Constants MyConstants
{
get { return myConstants; }
set { myConstants = value; }
}
public MainWindow()
{
MyConstants = new Constants();
InitializeComponent();
DataContext = this;
}
}
<Grid>
<TextBlock Text="{Binding MyConstants.TestDic[KEY_Test3]}"/>
</Grid>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.