从xaml中的Binding为Flyout实例化新对象

时间:2015-03-10 06:05:01

标签: windows-runtime winrt-xaml

在XAML中可能无法实现我想要实现的目标。如果有可能那么它可能是由于XAML功能值得了解。如果没有,那么我也学到了一些东西。

我有一个按钮弹出窗口,它与视图模型绑定数据。视图模型通过get访问器为弹出按钮的内容提供对象的新实例。

每次按下按钮,我都希望弹出窗口呈现对象的新实例。

Object created from ViewModel presented in flyout, on button press

问题:对象只创建一次,每次打开弹出按钮时都会重新显示。

ViewModel.cs

    class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class ViewModel
{
    static int itemCount;

    public Item GetNewItem {
        get {
            itemCount++;
            Debug.WriteLine("Created item: " + itemCount);
            return new Item() { Id = itemCount, Name = "Item_" + itemCount} ;
        }
    }


}

MainPage.xaml.cs

    <Page.Resources>
    <local:ViewModel x:Key="ViewModel"/>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
      DataContext="{StaticResource ViewModel}">
    <Button Content="Create Item">
        <Button.Flyout>
            <Flyout>
                <StackPanel DataContext="{Binding Path=GetNewItem}">
                    <TextBlock Text="{Binding Path=Id}"/>
                    <TextBlock Text="{Binding Path=Name}"/>
                </StackPanel>
            </Flyout>
        </Button.Flyout>
    </Button>

</Grid>

输出:

跟踪声明&#34;创建项目:Item_1&#34;出现,但不是&#34;创建了Item_2&#34;等等。

每次按下按钮时,都会显示相同的数据(&#34; 1&#34;和&#34; Item_1&#34;)。

研究

  1. 我可以在主页的代码隐藏中使它工作。我命名网格,并向弹出窗口添加一个Opening事件处理程序

    private void Flyout_Opening(object sender, object e) {
        var gridDataContext = (ViewModel)this.grid.DataContext;
        this.stackPanel.DataContext = gridDataContext.GetNewItem;
    }
    
  2. 现在工作正常! (但我想在XAML中这样做)

    1. 我尝试在ViewModel上实现INotifyPropertyChanged,但这没有用。

      class ViewModel:INotifyPropertyChanged {     static int itemCount;

      public Item GetNewItem {
          get {
              itemCount++;
              Debug.WriteLine("Created item: " + itemCount);
              OnPropertyChanged("GetNewItem");
              return new Item() { Id = itemCount, Name = "Item_" + itemCount} ;
          }
      }
      
      public event PropertyChangedEventHandler PropertyChanged;
      
      protected void OnPropertyChanged(string name) {
          var handler = PropertyChanged;
          if (handler != null) {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
      

0 个答案:

没有答案
相关问题