2015-12-22 95 views
0

我有一個GridView,與此項目模板(XAML):更改GridView中項目的屬性?

<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 權現在,如果我點擊gridview中的任何按鈕,它將調用implementcommand。不過,我想讓implementcommand對TextBlock控件做些什麼,例如更改文本的內容。從mainpage類中的任何函數中,如果它不在gridview中,它就像textBlock->Text = ref new String("hello");一樣簡單。但是,由於控件位於gridview中,並且實現命令函數位於MyClass而不是MainPage,所以我沒有知道如何做到這一點。

回答

0

在您的DataTemplate中的TextBlock中,您將Text綁定到MyString屬性,該屬性(與我所看到的綁定進行判斷)存在於與命令相同的類中。

你需要做的是

  1. 在你implementcommand改變的MyString
  2. 的價值
  3. 呼叫 Bindings.Update()

也有另一種方式(之前的經典方式X:綁定可用)

  1. 變化將TextBlock至O的結合模式neWay
  2. 在您的課程中實現INotifyPropertyChanged
  3. 在您的實現命令中更改MyString的值並引發INotifyPropertyChanged事件。
+0

感謝您的回答。我怎麼會從MyClass裏面調用Bindings.Update()呢? '綁定'在'MainPage'中,所以我無法訪問它... – justanotherxl

+0

好吧,我想出了一個解決方案,我以前的評論。我把'friend ref class MyClass'放在'MainPage'類中,然後在'MyClass'的構造函數中,我放了'MyClass(MainPage x)'。然後我用'MyClass(this)'調用構造函數'然後通過執行'x-> Bindings-> Update()'來訪問'MainPage'的成員。然而,'Bindings-> Update()'只會更新gridview之外的控件。 GridView內部的任何內容都沒有更新,如果我沒有任何綁定的GridView外的控件,應用程序會拋出一個nullptr異常。有任何想法嗎? – justanotherxl

+0

@justanotherxl查看[這篇文章](https://social.msdn.microsoft.com/Forums/en-US/5e0a094f-00b9-4de8-aca0-4a27b333b54d/xbind-only-working-after-two-updates- classic-bind-works-fine?forum = wpdevelop)來查看調用Bindings.Update的更好方法。你的Page對MyClass的依賴比反過來更好。 我想不出爲什麼Bindings.Update會更新GridView外的其他所有東西。你改變了GridView的DataContext嗎? – Corcus

相關問題