【问题标题】:Data Binding not working in silverlight数据绑定在 Silverlight 中不起作用
【发布时间】:2015-10-14 11:56:15
【问题描述】:

我正在尝试做一些简单的数据绑定。我有一个集合,它返回一个具有名为 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)
            {

            }
        }

我想我遗漏了一些明显的东西。你怎么看?

【问题讨论】:

  • 好的,我通过将 INotifyPropertyChanged 添加到我的类并添加相应的 PropertyChanged 事件来解决它。

标签: c# wpf wcf silverlight windows-phone-8.1


【解决方案1】:

使用页面的DataContext,如果未设置其数据上下文,则每个控件将使用该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 Main Page Instantiation and Loading Strategy for Easier Binding 的博客文章中给出了一个关于绑定、数据上下文和 MVVM 的简短示例。

【讨论】:

    【解决方案2】:

    我建议您使用“StandardUI”作为视图(或 LayoutRoot)的 DataContext,然后使用“MenuItems”作为 StackPanel 的 ItemsSource。然后,您可以根据需要向 StandardUI 添加许多属性,并在其他控件上使用它们。像 mvvm 模式。 ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-17
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多