在 Windows Phone 中操作 DataContext
我有一个非常小的应用程序,其中有一个笑话列表,一切正常,但每次我想在 TextBlock 中显示信息时,我都必须重新设置 DataContext。 TextBlock 在同一页面中发生变化,我只想更改笑话 ID 以获得新笑话。
private IList<Jokes> data;
Array variable;
private int count;
// Constructor
// ObservableCollection<Jokes> = new ObservableCollectoin<Jokes>;
public MainPage()
{
InitializeComponent();
JokeRepository countryRepository = new XmlJokeRepository();
data = countryRepository.GetCountryList().ToList<Jokes>();
DataContext = countryRepository.GetCountryById(3);
}
private void nextIconClick(object sender, EventArgs e)
{
Random rand = new Random();
int holder = rand.Next(1, count);
DataContext = data.FirstOrDefault(c => c.ID == holder);
}
在我的 XAML 中,{Binding Description} 属性可以正常工作,但我确实觉得这是多余且无用的。尽管我仍然使用相同的变量/页面,是否有另一种方法可以解决这个问题,而不必每次都重置 DataContext?
I have a really small application where I have a list of jokes, everything is working properly but I have to re-set DataContext everytime I want to display the information in the TextBlock. The TextBlock changes in the SAME page, I only want to change the joke ID to get the new joke.
private IList<Jokes> data;
Array variable;
private int count;
// Constructor
// ObservableCollection<Jokes> = new ObservableCollectoin<Jokes>;
public MainPage()
{
InitializeComponent();
JokeRepository countryRepository = new XmlJokeRepository();
data = countryRepository.GetCountryList().ToList<Jokes>();
DataContext = countryRepository.GetCountryById(3);
}
private void nextIconClick(object sender, EventArgs e)
{
Random rand = new Random();
int holder = rand.Next(1, count);
DataContext = data.FirstOrDefault(c => c.ID == holder);
}
Where in my XAML I have the {Binding Description} property working correctly, but I really feel this redundant and useless. Is there another way to work this without having to reset DataContext everytime although I still use the same variable/page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个属性,例如
CurrentJoke
,然后将您的DataContext
设置为该属性。然后,您可以更新该属性并触发
NotifyPropertyChanged
事件,该事件将使用CurrentJoke
属性中的最新数据刷新TextBox
。下面是一个(未经测试但非常接近)代码示例:
在 XAML 中,设置使用与
Description
相同的{Binding CurrentJoke}
语法。如果您正确地进行了一个字段数据绑定,则整个页面的DataContext
可能已经正确设置。You could create a property such as
CurrentJoke
, then set yourDataContext
to that.Then you could just update that property and fire a
NotifyPropertyChanged
event, which will refresh theTextBox
with the latest data from yourCurrentJoke
property.Here's an (untested but pretty close) code sample:
In your XAML, set use the same
{Binding CurrentJoke}
syntax you used for theDescription
. TheDataContext
is probably already set correctly for the whole page if you have one field databinding correctly.