[英]Data Binding not working in silverlight
我正在嘗試做一些簡單的數據綁定。 我有一個集合,返回一個帶有名為MenuName的屬性的項目。 我檢查了它是否正確返回。 因此,這就是我嘗試進行綁定的方式。 (通過Menu繼承自INotifyPropertyChanged。)
XAML
<Grid x:Name="LayoutRoot" DataContext="MenuItems">
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Grid.Row="0" Margin="24,17,0,28">
<TextBlock Text="Test" Typography.Capitals="SmallCaps"/>
<TextBlock Text="{Binding MenuName }" Margin="0,12,0,0" FontSize="52"/>
<CheckBox>Cache</CheckBox>
</StackPanel>
</Grid>
背后的代碼:
#region Members
MyAppWinConnectionClient MyAppWinService;
#endregion Members
#region Properties
public ObservableCollection<Menu> MenuItems { get; set; }
#endregion Properties
public StandardUI()
{
MyAppWinService = new MyAppWinConnectionClient();
this.InitializeComponent();
LoadTest();
}
private async void LoadTest()
{
try
{
MenuItems = await MyAppWinService.GetMenuEntriesAsync();
}
catch (FileNotFoundException ex)
{
}
}
我想我缺少明顯的東西。 你怎么看?
我建議您將“ StandardUI”用作視圖(或LayoutRoot)的DataContext,然后將“ MenuItems”用作StackPanel的ItemsSource。 然后,您可以根據需要向StandardUI添加許多屬性,並在其他控件上使用它們。 就像mvvm模式。 ;)
如果未設置其數據上下文,則使用每個控件將使用的頁面的DataContext
。 這樣設置頁面的數據上下文:
public StandardUI()
{
DataContext = this;
MyAppWinService = new MyAppWinConnectionClient();
this.InitializeComponent();
LoadTest();
}
然后在綁定上,提取第一個菜單項:
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBlock Text="Test" Typography.Capitals="SmallCaps"/>
<TextBlock Text="{Binding MenuItems[0].MenuName }" />
<CheckBox>Cache</CheckBox>
</StackPanel>
</Grid>
但是應該研究MVVM。 我在我的博客文章Xaml:ViewModel主頁實例化和更輕松綁定的加載策略上給出了綁定,數據上下文和MVVM的簡短示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.