-1

我正在用c#開發windows 10通用應用程序。 我有一個UserControl是MyListview項目模板。 Listview將綁定數據。在userControl中,有一個用於刪除usercontrol DependencyProperty Content(包含字符串Text,Name和int Id)的按鈕。如何通過UserControl模板中的函數刪除ListView項目?

Listview顯示對象的文本和刪除它的按鈕。

現在如何通過單擊刪除按鈕從我的列表中刪除該項目?

更新

我的數據類:

class Data 
    { 
     public int Id { get; set; } 
     public string Text { get; set; } 
    } 

我usercontrol.cs:

public Data Content 
{ 
    get { return (Data)GetValue(ContentProperty); } 
    set { SetValue(ContentProperty, value); } 
} 

// Using a DependencyProperty as the backing store for Content. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty ContentProperty = 
      DependencyProperty.Register("Content", typeof(Data), typeof(MyUserControl1), new PropertyMetadata(null)); 

用戶控件XAML:

<StackPanel> 
    <TextBlock x:Name="textBlock" Text="{Binding Content.Text, ElementName=textBlock}" /> 
    <Button Click="Remove_Click"/> 
</StackPanel> 

我的列表執行:

<Page.Resources> 
     <DataTemplate x:Key="ListViewTemplate"> 
      <local:MyUserControl1 Content="{Binding}"/> 
     </DataTemplate> 
</Page.Resources> 
<Grid> 
    <ListView x:Name="ListView" ItemTemplate="{StaticResource ListViewTemplate}" /> 
</Grid> 

,並在代碼behinde頁我用一個ObservableCollection<Data> items = new ObservableCollection<Data>();設置Listview.ItemsSource它。

的主要問題是如何從items刪除MyUsercontrol1

+0

所以你不要如何實現Remove_Click,你呢? –

+0

@MichałKomorowski是的,我想按刪除按鈕和項目從列表中刪除 –

回答

1

該項目你寫的綁定,所以我假設你的XAML是有下面的代碼或類似:

<ListView ItemSource = "{Bind SomeCollection"} ... /> 

如果我是對的,那就沒有什麼可做的了。如果SomeCollection的類型爲ObservableCollection<T>,那麼從SomeCollection中刪除一個項目就足夠了,UI將自動刷新。總結:

  1. 聲明SomeCollectionObservableCollection<T>
  2. 在當點擊刪除按鈕(或在事件處理程序)時執行的命令簡單地調用ObservableCollection<T>.Remove

UPDATE

此代碼是不優雅,但顯示了一個主意。首先,我們需要修改Data類:

public class Data 
{ 
    public int Id { get; set; } 
    public string Text { get; set; } 
    public Action<Data> OnRemoveCallback { get; set; } 

    public void OnRemove() 
    { 
     OnRemoveCallback(this); 
    } 
} 

OnRemoveCallback將用於通知ListView一個給定的數據元素應該被刪除。Remove_clickMyUserControl處理程序僅執行OnRemove

private void Remove_Click(object sender, RoutedEventArgs e) 
{ 
    Content.OnRemove(); 
} 

最後,在後面的Page我們要定義將負責從列表中實際刪除數據項的邏輯代碼:

public void Remove(Data d) 
{ 
    ((ObservableCollection<Data>) ListView.ItemsSource).Remove(d); 
} 

...

ListView.ItemsSource = new ObservableCollection<Data>() 
{ 
    new Data() {Id = 1, Text = "1", OnRemoveCallback = Remove}, 
    new Data() {Id = 2, Text = "2", OnRemoveCallback = Remove} 
}; 

現在您的頁面將被通知刪除按鈕被按下,並會做的工作。

正如我說,這是不是一個完美的解決方案。就個人而言,我將使用MVVM模式。謝謝你做XAML和C#將分離。

+0

我使用的ObservableCollection 但主要問題是如何從MyUserControle刪除。 –

+0

@AliMalek你需要從集合,而不是用戶控件本身刪除的數據項。如果您刪除該項目,UserControl將被列表中刪除。 –

+0

但它正在從的ObservableCollection 集合中刪除。現在,我不明白你想達到什麼。 –