【问题标题】:Change property of an item inside a GridView?更改 GridView 中项目的属性?
【发布时间】:2015-12-22 21:33:18
【问题描述】:

我有一个 GridView,带有这个项目模板 (XAML):

<DataTemplate x:DataType="local:MyClass">
      <TextBlock Text="{x:Bind MyString}"/>
      <Button Command="{x:Bind command}"/>
</DataTemplate>

这里是MyClass (C++/CX)

public ref class MyClass sealed
{
 public:
     MyClass();
     property Platform::String^ MyString
     {
          String^ get()
            {
               return mystring;
            }
     }
     property ICommand^ command = ref new DelegateCommand(ref new ExecuteDelegate(this, &implementcommand), nullptr);
     private:
         String^ mystring;
         void implementcommand(Platform::Object^ param);
}

DelegateCommand 函数是从此示例中提取的,未经修改:https://code.msdn.microsoft.com/windowsapps/Command-binding-inside-3cef5eea 现在,如果我单击网格视图中的任何按钮,它将调用implementcommand。但是,我想让implementcommand 对 TextBlock 控件做一些事情,例如更改文本的内容。从mainpage类内的任何函数,如果它不在gridview内,它就像textBlock-&gt;Text = ref new String("hello");一样简单但是,由于控件在gridview内,而implementcommand函数在MyClass中,不是MainPage,我不知道该怎么做。

【问题讨论】:

    标签: xaml gridview data-binding uwp c++-cx


    【解决方案1】:

    在 DataTemplate 的 TextBlock 中,您将 Text 绑定到 MyString 属性,该属性(根据我看到的绑定判断)与命令存在于同一类中。

    你需要做的是

    1. 在您的 implementcommand 中更改 MyString 的值
    2. 呼叫 Bindings.Update()

    还有另一种方式(x:Bind之前的经典方式)

    1. 将TextBlock中的绑定方式改为OneWay
    2. 在你的类中实现 INotifyPropertyChanged
    3. 在您的实施命令中更改 MyString 的值并引发 INotifyPropertyChanged 事件。

    【讨论】:

    • 感谢您的回答。我如何从MyClass 内部调用 Bindings.Update() 呢? BindingsMainPage,所以我无法访问它...
    • 好的,我找到了解决我之前评论的方法。我把friend ref class MyClass放在MainPage类中,然后在MyClass的构造函数中,我把MyClass(MainPage x)。然后我用MyClass(this) 调用构造函数然后我可以通过x-&gt;Bindings-&gt;Update() 访问MainPage 的成员。但是,Bindings-&gt;Update() 只为我更新了 gridview 之外的控件。 GridView 内的任何内容都没有更新,如果我在 gridview 之外没有任何绑定控件,则应用程序会抛出带有 nullptr 的异常。有什么想法吗?
    • @justanotherxl 查看this post 了解调用 Bindings.Update 的更好方法。您的 Page 最好依赖 MyClass 而不是相反。我想不出 Bindings.Update 更新 GridView 之外的所有其他内容的原因。你改变了 GridView 的 DataContext 了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多