单击每个ListViewItem的Button时修改TextBlock值

时间:2016-02-27 21:02:22

标签: c# win-universal-app windows-10-universal

我有ListView的代码:

 <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”按钮,每个Button都有一个“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));
        }
    }
}

那么,当我点击每个ListViewItem的BtnStar按钮时,如何修改TextBlock的值 谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

好。首先,您需要在xaml应用程序中使用绑定方法。

你的类Locals实现了INotifyPropertyChanged,但实现不好。 请查看此示例:

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

{

get
 {
   return someProperty;
 }
 set
 {
   someProperty =value;
   NotifyPropertyChanged("SomeProperty");
 }
}
你的文本块中的

你有Text = {Binding SomeProperty}

你需要添加Mode = TwoWay

Text = {Binding SomeProperty,Mode = TwoWay}

最后在你的点击方法中 btnStar_Click

你需要做这样的事情:

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

如果您在模型中正确实现了INotifyPropertyChanged,您将在UI中看到更改。

就是这样。

如果它对您有用,请标记此答案!

最诚挚的问候。