2016-02-27 47 views
0

我有這樣的代碼爲我的ListView按鈕:修改TextBlock的值當點擊的每一個ListViewItem

<ListView x:Name="listme"> 
<ListView.ItemTemplate > 
    <DataTemplate > 
    <Grid> 
     ... 
     <Button Background="{Binding ButtonColor}" x:Name="btnStar" 
Click="btnStar_Click" Tag={Binding}> 
      <Image/> 
      <TextBlock Text="{Binding Path=all_like}" x:Name="liketext" /> 
     </Button> 
    </Grid> 
    </DataTemplate > 
</ListView.ItemTemplate > 
</ListView > 

我有2個ListviewItems,每個人心中都有一個「BtnStar」按鈕,每個按鈕都有一個「liketext」 TextBlock,其中一個TextBlocks僅適用於每個示例,當我點擊ListViewItem1的btnStar時,它修改了ListViewItem2的TextBlock的TextBlock值,當我點擊ListViewItem1的BtnStar時,我無法修改ListViewItem1的TextBlock文本,這是我的代碼:

ObservableCollection<Locals> Locals = new ObservableCollection<Locals>(); 
    public async void getListePerSearch() 
    { 
     try 
     { 
      UriString2 = "URL"; 
      var http = new HttpClient(); 
      http.MaxResponseContentBufferSize = Int32.MaxValue; 
      var response = await http.GetStringAsync(UriString2); 
      var rootObject1 = JsonConvert.DeserializeObject<NvBarberry.Models.RootObject>(response); 

      foreach (var item in rootObject1.locals) 
       { 
        Item listItem = new Item(); 
        if (listItem.all_like == null) 
         { 
          listItem.all_like = "0"; 
         } 

       listme.ItemsSource = Locals; 
    } 
     private void Button_Click(object sender, RoutedEventArgs e) 
       { 
        var btn = sender as Button; 
        var item = btn.Tag as Locals; 
        item.all_like = liketext.Text; 
        liketext.Text = (int.Parse(item.all_like) + 1).ToString(); 
        } 

Locals.cs:

public class Locals : INotifyPropertyChanged 
{ 
    public int id_local { get; set; } 
    public string all_like { get; set; } 


    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, 
       new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

所以,我怎麼能修改TextBlock的價值時,我在每一個ListViewItem 感謝的BtnStar按鈕單擊幫助

+0

任何幫助請:( – user3821206

回答

1

嘛。首先你需要在xaml應用中使用綁定方法。

你的類本地實現INotifyPropertyChanged,但實現不好。 請檢查下面的例子:

public string someProperty {get;set;} 
public string SomeProperty 

{ 

get 
{ 
    return someProperty; 
} 
set 
{ 
    someProperty =value; 
    NotifyPropertyChanged("SomeProperty"); 
} 
} 
在你的文字塊

你有文字= {結合SomeProperty}

你需要添加模式=雙向

文本= {結合SomeProperty,模式=雙向}

終於在點擊方法 btnStar_Click

你需要做的是這樣的:

var btn = sender as Button; 
var local= btn.DataContext as Local; 
local.SomeProperty= "my new value" 

如果您在模型中正確實施了INotifyPropertyChanged,則會在UI中看到更改。

就是這樣。

請標記此答案,如果它對你有用!

最好的問候。

+1

請標記此答案,如果它對您有用!祝好! – RicardoPons

+0

非常感謝先生現在的作品:D – user3821206