簡體   English   中英

C#WPF如何在后面的代碼中獲取綁定值

[英]C# WPF How to get binding value in code behind

我有一個帶有2個textbox和一個button的自定義控件ChatTextControl xaml是這樣的:

<Grid Background="White">
    <Grid.ColumnDefinitions>
        <!-- Message -->
        <ColumnDefinition Width="*"/>
        <!-- delete message -->
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <!-- Message content -->
    <StackPanel>
        <TextBlock Text="{Binding Path= Pseudo}" FontWeight="SemiBold"/>
        <TextBlock Text="{Binding Path= Message}" TextWrapping="Wrap"/>
    </StackPanel>

    <Button Grid.Column="1" Padding="8" VerticalAlignment="Top" Width="20" Height="20" Background="{x:Null}" Click="Button_Click"/>
</Grid>

偽和消息來自以下類:

public class ChatListItemViewModel : BaseViewModel
{
    public string Pseudo { get; set; }

    public string Message { get; set; }

    public int Id { get; set; }
}

在另一個自定義控件ChatTextControl中調用ChatListControl

<Grid Background="White">
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <ItemsControl ItemsSource="{Binding Items}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <local:ChatTextControl />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</Grid>

在我的主窗口中,我這樣調用ChatListControl

<local:ChatListControl x:Name="MyChat" Margin="389,10,10,38"/>

並在代碼后面設置DataContext:

ChatListModel chat = new ChatListModel();
MyChat.DataContext = chat;

ChatListModel:

public class ChatListModel : ChatListViewModel
{
    private static int idCount = 0;

    public ChatListModel()
    {
        Items = new List<ChatListItemViewModel>();
    }

    public void AddMessage(string p, string m)
    {
        Items.Add(new ChatListItemViewModel
        {
            Pseudo = p,
            Message = m,
            Id = idCount
        });
        idCount++;
    }
}

目標是使用ChatTextControl的Button_Click事件刪除列表中具有相應ID的元素。 但是我不知道如何在ChatTextControl.csMainWindow.cs中的代碼后面獲取ID。

如果有人知道該怎么做或對刪除按鈕有更好的主意,請告訴我。

例如,您可以在單擊按鈕時在ChatListItemViewModel設置IsDelete屬性,引發事件並在ChatListModel處理此事件。 您需要使用ObservableCollecton<T>而不是List<T>來在視圖中刪除該項目:

public class ChatListModel : ChatListViewModel
{
    private static int idCount = 0;

    public ChatListModel()
    {
        Items = new ObservableCollection<ChatListItemViewModel>();
        AddMessage("p", "m");
    }

    public void AddMessage(string p, string m)
    {
        ChatListItemViewModel newItem = new ChatListItemViewModel
        {
            Pseudo = p,
            Message = m,
            Id = idCount
        };
        newItem.PropertyChanged += NewItem_PropertyChanged;
        Items.Add(newItem);
        idCount++;
    }

    private void NewItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        ChatListItemViewModel removedItem = (ChatListItemViewModel)sender;
        removedItem.PropertyChanged -= NewItem_PropertyChanged;
        Items.Remove(removedItem);
        idCount--;
    }

    public ObservableCollection<ChatListItemViewModel> Items { get; }
}

public class ChatListItemViewModel : BaseViewModel
{
    public string Pseudo { get; set; }

    public string Message { get; set; }

    public int Id { get; set; }

    private bool _isDeleted;
    public bool IsDeleted
    {
        get { return _isDeleted; }
        set { _isDeleted = value; OnPropertyChanged(nameof(IsDeleted)); }
    }

    public ChatListItemViewModel()
    {
        DeleteCommand = new RelayCommand(_ => true, _ => IsDeleted = true);
    }

    public ICommand DeleteCommand { get; }
}

ChatTextControl.xaml:

<Button Grid.Column="1" Padding="8" VerticalAlignment="Top" Width="20" Height="20" 
        Background="{x:Null}" Command="{Binding DeleteCommand}" />

由於評論中的原因,我無法驗證mm8的答案,因此這是我找到的解決方案。

在Button_Click事件中放置斷點后,我注意到可以通過在this.DataContextChatTextControl轉換ChatTextControl並發送如下事件來獲取ChatListItemViewModel的ID:

    public delegate void DeleteClick(int id);
    public static event DeleteClick OnDeleteClick;
    private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        OnDeleteClick?.Invoke(((ChatListItemViewModel)this.DataContext).Id);
    }

這樣做,我可以獲取ID並在主窗口中刪除該項目:

    public ChatListModel chat;
    public MainWindow()
    {
        InitializeComponent();
        chat = new ChatListModel();
        chat.AddMessage(name, "Hello World!");
        MyChat.DataContext = chat;
        ChatTextControl.OnDeleteClick += ChatTextControl_OnDeleteClick;
    }

    private void ChatTextControl_OnDeleteClick(int id)
    {
        chat.DelMessage(id);
        MyChat.DataContext = null;
        MyChat.DataContext = chat;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM