【问题标题】:Silverlight DataBinding MVVMSilverlight 数据绑定 MVVM
【发布时间】:2011-05-15 20:12:53
【问题描述】:

我在 Silverlight 中设置数据绑定时遇到了一些问题。

我尝试使用 MVVM 方法并找到了一些不错的示例,因此我创建了我的 View 和我的 ViewModel,我创建了一些用于包含数据的类和一个用于填充类的类。

首先我的 ViewModel 看起来像:

 public class MainPageVM : INotifyPropertyChanged
    {
        ObservableCollection<Item> Items;
        public MainPageVM()
        {
            InitializeItems InitItems = new InitializeItems();
            InitItems.GenerateItemList(out Items);
            RaiseProertyChanged("Items");
        }
        public string test = "Binding Test";

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        private void RaiseProertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

然后在我看来,我有:

<UserControl.Resources>
    <viewmodel:MainPageVM x:Key="ViewModel" />    
</UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}">
    <StackPanel>
        <TextBlock Text="{Binding test}"/>
        <ListBox ItemsSource="{Binding Items}"
             Width="200"
             Height="200">
            <ListBoxItem Width="190" Height="20">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding ItemName}"/>
                    <TextBlock Text="-"/>
                    <TextBlock Text="{Binding ItemID}"/>
                </StackPanel>
            </ListBoxItem>
        </ListBox>
    </StackPanel>
</Grid>

我添加了断点,并且我知道我试图绑定的 ObservableCollection 正在被填充,但没有任何绑定,在错误窗口中我只是获取 MainPageVM 中不存在 xxx 属性。

这里的任何建议都会很棒,因为我对可能发生的事情有点迷茫,这是我的第一个 Silverlight 应用程序。

谢谢

【问题讨论】:

  • 为什么有人反对这个?

标签: silverlight xaml binding


【解决方案1】:

Items 必须是公共属性。与您的测试领域相同。在 Silverlight 中,您只能绑定到公共属性。

此外,通常在这些属性的 Setter 中,您会引发属性更改事件。这告诉 Silverlight 运行时用该属性的新值刷新绑定到该属性的控件。

【讨论】:

  • 谢谢,我认为它可以让我直接绑定到公共变量而不是属性。
猜你喜欢
  • 2011-04-16
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 2012-05-25
  • 2013-01-07
  • 1970-01-01
相关资源
最近更新 更多