通過Demo學WPF—數據綁定(二)

来源:https://www.cnblogs.com/mingupupu/p/18000305
-Advertisement-
Play Games

準備 今天學習的Demo是Data Binding中的Linq: 創建一個空白解決方案,然後添加現有項目,選擇Linq,解決方案如下所示: 查看這個Demo的效果: 開始學習這個Demo xaml部分 查看MainWindow.xaml: <Window x:Class="Linq.MainWind ...


準備

今天學習的Demo是Data Binding中的Linq:

image-20240131155033495

創建一個空白解決方案,然後添加現有項目,選擇Linq,解決方案如下所示:

image-20240131155225236

查看這個Demo的效果:

這個Demo的效果

開始學習這個Demo

xaml部分

查看MainWindow.xaml

<Window x:Class="Linq.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Linq"
        mc:Ignorable="d"
        Title="MainWindow" SizeToContent="WidthAndHeight" Height="600">
    <Window.Resources>
        <local:Tasks x:Key="MyTodoList"/>
        <DataTemplate x:Key="MyTaskTemplate">
            <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
              Padding="5" Margin="5">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="Task Name:"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}" />
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Description:"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="Priority:"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
                </Grid>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <TextBlock Margin="10,0,0,0">Choose a Priority:</TextBlock>
        <ListBox SelectionChanged="ListBox_SelectionChanged"
                 SelectedIndex="0" Margin="10,0,10,0" >
            <ListBoxItem>1</ListBoxItem>
            <ListBoxItem>2</ListBoxItem>
            <ListBoxItem>3</ListBoxItem>
        </ListBox>
        <ListBox Width="400" Margin="10" Name="myListBox"
                 HorizontalContentAlignment="Stretch"
                 ItemsSource="{Binding}"
                 ItemTemplate="{StaticResource MyTaskTemplate}"/>

    </StackPanel>
</Window>

先來看看資源包含什麼內容(省略子項):

<Window.Resources>
        <local:Tasks x:Key="MyTodoList"/>
        <DataTemplate x:Key="MyTaskTemplate">      
        </DataTemplate>
</Window.Resources>

<Window.Resources> 是 XAML 中的一個元素,它定義了一個資源字典,你可以在其中聲明和存儲可在整個視窗中重用的資源。

我們發現包含兩個資源:一個 Tasks 對象和一個 DataTemplate。

通過上一篇文章的學習,我們明白

<local:Tasks x:Key="MyTodoList"/>

的意思就是創建了一個 Tasks 對象,並給它分配了一個鍵(key)MyTodoList。這樣你就可以在其他地方通過這個鍵引用這個 Tasks 對象了。

DataTemplate又是什麼呢?

image-20240131161807052

<DataTemplate x:Key="MyTaskTemplate">
            <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
              Padding="5" Margin="5">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="Task Name:"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}" />
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Description:"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Text="Priority:"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
                </Grid>
            </Border>
        </DataTemplate>

其中<DataTemplate x:Key="MyTaskTemplate"> 是 XAML 中的一個元素,它定義瞭如何將數據對象呈現為 UI 元素。
在這個例子中,DataTemplate 定義了一個模板,該模板描述瞭如何將數據呈現在 UI 中。這個模板被賦予了一個鍵(key),即 MyTaskTemplate,這樣你就可以在其他地方引用這個模板了。

 <Grid>
    <Grid.RowDefinitions>
         <RowDefinition/>
         <RowDefinition/>
          <RowDefinition/>
     </Grid.RowDefinitions>
     <Grid.ColumnDefinitions>
          <ColumnDefinition />
          <ColumnDefinition />
      </Grid.ColumnDefinitions>
 <Grid>    

定義了一個3行2列的Grid佈局:

image-20240131162453337

 <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}" />

Grid.Row="0"表示第1行,Grid.Column="1"表示第2列,Text="{Binding Path=TaskName}" 表示Text屬性的值為綁定源的TaskName屬性的值。

   <TextBlock Margin="10,0,0,0">Choose a Priority:</TextBlock>
    <ListBox SelectionChanged="ListBox_SelectionChanged"
             SelectedIndex="0" Margin="10,0,10,0" >
        <ListBoxItem>1</ListBoxItem>
        <ListBoxItem>2</ListBoxItem>
        <ListBoxItem>3</ListBoxItem>
    </ListBox>

表示以下這部分:

image-20240131163013465

<ListBox Width="400" Margin="10" Name="myListBox"
         HorizontalContentAlignment="Stretch"
         ItemsSource="{Binding}"
         ItemTemplate="{StaticResource MyTaskTemplate}"/>

表示以下這部分:

image-20240131163113558

image-20240131163134246

我們會發現它沒有顯式的寫 <ListBoxItem>,而且它的ListBoxItem數量不是固定的。

它使用了ItemsSource="{Binding}"ItemsSource 是 ListBox 的一個屬性,它決定了 ListBox 中顯示的項的數據源。

{Binding} 是一個標記擴展,它創建一個數據綁定。在這個例子中,由於沒有指定路徑(Path),所以它會綁定到當前的數據上下文(DataContext)。數據上下文通常在父元素中設置,並且所有的子元素都可以訪問。

ItemTemplate="{StaticResource MyTaskTemplate}"表示每個<ListBoxItem>對象將按照這個模板進行顯示。

cs部分

首先定義了TaskType枚舉類型:

namespace Linq
{
    public enum TaskType
    {
        Home,
        Work
    }
}

定義了Task類:

// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace Linq
{
    public class Task : INotifyPropertyChanged
    {
        private string _description;
        private string _name;
        private int _priority;
        private TaskType _type;

        public Task()
        {
        }

        public Task(string name, string description, int priority, TaskType type)
        {
            _name = name;
            _description = description;
            _priority = priority;
            _type = type;
        }

        public string TaskName
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("TaskName");
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                OnPropertyChanged("Description");
            }
        }

        public int Priority
        {
            get { return _priority; }
            set
            {
                _priority = value;
                OnPropertyChanged("Priority");
            }
        }

        public TaskType TaskType
        {
            get { return _type; }
            set
            {
                _type = value;
                OnPropertyChanged("TaskType");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString() => _name;

        protected void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

實現了INotifyPropertyChanged介面。

實現INotifyPropertyChanged介面的主要目的是為了提供一個通知機制,當對象的一個屬性更改時,可以通知到所有綁定到該屬性的元素。

INotifyPropertyChanged 介面只有一個事件 PropertyChanged。當你的類實現了這個介面,你需要在每個屬性的 setter 中觸發這個事件。這樣,當屬性的值更改時,所有綁定到這個屬性的 UI 元素都會收到通知,並自動更新其顯示的值。

再查看Tasks類:

// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace Linq
{
    public class Tasks : ObservableCollection<Task>
    {
        public Tasks()
        {
            Add(new Task("Groceries", "Pick up Groceries and Detergent", 2, TaskType.Home));
            Add(new Task("Laundry", "Do my Laundry", 2, TaskType.Home));
            Add(new Task("Email", "Email clients", 1, TaskType.Work));
            Add(new Task("Clean", "Clean my office", 3, TaskType.Work));
            Add(new Task("Dinner", "Get ready for family reunion", 1, TaskType.Home));
            Add(new Task("Proposals", "Review new budget proposals", 2, TaskType.Work));
        }
    }
}

繼承自ObservableCollection<Task>類。

ObservableCollection<T> 是 .NET 框架中的一個類,它表示一個動態數據集合,當添加、刪除項或者整個列表刷新時,它會提供通知。這對於綁定到 UI 元素(例如 WPF 或 UWP 應用程式中的數據綁定)非常有用,因為當集合更改時,UI 元素可以自動更新。

image-20240131164317743

再看下這個Demo中最為重要的部分:

// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Linq
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Tasks tasks = new Tasks();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var pri = int.Parse(((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString());

            DataContext = from task in tasks
                where task.Priority == pri
                select task;     
        }
    }
}
 private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var pri = int.Parse(((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString());

            DataContext = from task in tasks
                where task.Priority == pri
                select task;     
        }

表示ListBox選項改變事件處理函數。

 var pri = int.Parse(((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString());

獲取選中項的值。

   DataContext = from task in tasks
                where task.Priority == pri
                select task; 

中的DataContext獲取或設置元素參與數據綁定時的數據上下文。

image-20240131165019921

from task in tasks
where task.Priority == pri
select task; 

使用C#中的Linq獲得tasks中Priority屬性等於pri的所有task對象,也可以這樣寫:

  DataContext = tasks.Where(x => x.Priority == pri);

效果是一樣的。

過程

首先實例化了一個Tasks類如下:

image-20240131165631201

包含這些Task類。

以選擇“2”為例,進行說明:

image-20240131165511996

打個斷點:

image-20240131165821240

DataContext的結果如下:

image-20240131165934477

<ListBox Width="400" Margin="10" Name="myListBox"
         HorizontalContentAlignment="Stretch"
         ItemsSource="{Binding}"
         ItemTemplate="{StaticResource MyTaskTemplate}"/>

中的ItemsSource="{Binding}"表示ListBox的數據源就是DataContext,也就是有3個Task對象,也就是有3個ListItem,每個ListItem都按照{StaticResource MyTaskTemplate}這個模板進行顯示。

結果就如上圖所示。

測試

最後為了測試自己是否真的理解,可以按照自己的意圖進行更改,比如我想根據工作類型進行數據的顯示。

<TextBlock Grid.Row="2" Grid.Column="0" Text="TaskType:"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=TaskType}"/>

修改數據模板。

<ListBox SelectionChanged="ListBox_SelectionChanged"
         SelectedIndex="0" Margin="10,0,10,0" >
    <ListBoxItem>Home</ListBoxItem>
    <ListBoxItem>Work</ListBoxItem>
</ListBox>

修改第一個ListBox。

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var pri = ((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString();
    TaskType type = new TaskType();
    switch (pri)
    {
        case "Home":
            type = TaskType.Home;
            break;
        case "Work":
            type = TaskType.Work;
            break;
        default:
            break;
    }
    
    DataContext = tasks.Where(x => x.TaskType == type);
}

修改ListBox選項改變事件處理函數。

效果如下所示:

效果2

總結

本文主要介紹了數據綁定配合Linq的使用,希望對你有所幫助。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • MVVM-命令模式的實現與應用 本文同時為b站WPF課程的筆記,相關示例代碼 綁定 這個其實前面已經講過一部分 使用{Binding}設置數據綁定,將控制項的屬性綁定到 ViewModel 的相應屬性。 比如說需要註意,在xaml中綁定的不再是UserName和Password了,而是loginMod ...
  • 概述:在WPF中實現依賴註入和控制反轉,通過定義介面、實現類,配置容器,實現組件解耦、提高可維護性。 什麼是依賴註入和控制反轉? 依賴註入(Dependency Injection,DI): 是一種設計模式,旨在減少組件之間的耦合度。通過依賴註入,對象不再自行創建或查找依賴對象,而是通過外部註入的方 ...
  • 概述:WPF中的Template機製為界面定製提供了強大工具,包括控制項模板、ItemsPresenter、ItemsPanel、和ItemContainerStyle。通過這些功能,開發者能精確定義控制項外觀和佈局,個性化每個項的樣式,實現靈活而美觀的用戶界面。 WPF中各種Template功能用途: ...
  • 在進行WPF界面設計時,我們需要在很多地方設置顏色屬性,比如元素的背景色、前景色以及邊框的顏色,還有形狀的內部填充和筆畫,這些顏色的設置在WPF中都以畫刷(Brush)的形式實現。比如最常用的畫刷就是SolidColorBrush,它表示一種純色。 public abstract class Bru ...
  • 代碼片段: 文末附鏈接。 using DataSync.Core; using Furion.Logging.Extensions; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; using System.Da ...
  • Ultralytics YOLOv8 基於深度學習和電腦視覺領域的尖端技術,在速度和準確性方面具有無與倫比的性能。其流線型設計使其適用於各種應用,並可輕鬆適應從邊緣設備到雲 API 等不同硬體平臺。YOLOv8 OBB 模型是YOLOv8系列模型最新推出的任意方向的目標檢測模型,可以檢測任意方向的... ...
  • RotateTransform旋轉 RotateTransform表示旋轉一個對象的角度。首先我們來看一下它的定義 public sealed class RotateTransform : Transform { public static readonly DependencyProperty ...
  • 最近做了幾個 WPF + MudBlazor 的小東西,每次從頭搭建環境比較繁瑣,然鵝搭建過程還沒啥技術含量,索性就直接做了個模板,方便以後使用。 1. 介紹 一個用來創建 .NET 8 + WPF + MudBlazor 的項目模板 適用於 VS2022 用法:vs插件市場下載 or 自己通過 G ...
一周排行
    -Advertisement-
    Play Games
  • 前言 微服務架構已經成為搭建高效、可擴展系統的關鍵技術之一,然而,現有許多微服務框架往往過於複雜,使得我們普通開發者難以快速上手並體驗到微服務帶了的便利。為瞭解決這一問題,於是作者精心打造了一款最接地氣的 .NET 微服務框架,幫助我們輕鬆構建和管理微服務應用。 本框架不僅支持 Consul 服務註 ...
  • 先看一下效果吧: 如果不會寫動畫或者懶得寫動畫,就直接交給Blend來做吧; 其實Blend操作起來很簡單,有點類似於在操作PS,我們只需要設置關鍵幀,滑鼠點來點去就可以了,Blend會自動幫我們生成我們想要的動畫效果. 第一步:要創建一個空的WPF項目 第二步:右鍵我們的項目,在最下方有一個,在B ...
  • Prism:框架介紹與安裝 什麼是Prism? Prism是一個用於在 WPF、Xamarin Form、Uno 平臺和 WinUI 中構建鬆散耦合、可維護和可測試的 XAML 應用程式框架 Github https://github.com/PrismLibrary/Prism NuGet htt ...
  • 在WPF中,屏幕上的所有內容,都是通過畫筆(Brush)畫上去的。如按鈕的背景色,邊框,文本框的前景和形狀填充。藉助畫筆,可以繪製頁面上的所有UI對象。不同畫筆具有不同類型的輸出( 如:某些畫筆使用純色繪製區域,其他畫筆使用漸變、圖案、圖像或繪圖)。 ...
  • 前言 嗨,大家好!推薦一個基於 .NET 8 的高併發微服務電商系統,涵蓋了商品、訂單、會員、服務、財務等50多種實用功能。 項目不僅使用了 .NET 8 的最新特性,還集成了AutoFac、DotLiquid、HangFire、Nlog、Jwt、LayUIAdmin、SqlSugar、MySQL、 ...
  • 本文主要介紹攝像頭(相機)如何採集數據,用於類似攝像頭本地顯示軟體,以及流媒體數據傳輸場景如傳屏、視訊會議等。 攝像頭採集有多種方案,如AForge.NET、WPFMediaKit、OpenCvSharp、EmguCv、DirectShow.NET、MediaCaptre(UWP),網上一些文章以及 ...
  • 前言 Seal-Report 是一款.NET 開源報表工具,擁有 1.4K Star。它提供了一個完整的框架,使用 C# 編寫,最新的版本採用的是 .NET 8.0 。 它能夠高效地從各種資料庫或 NoSQL 數據源生成日常報表,並支持執行複雜的報表任務。 其簡單易用的安裝過程和直觀的設計界面,我們 ...
  • 背景需求: 系統需要對接到XXX官方的API,但因此官方對接以及管理都十分嚴格。而本人部門的系統中包含諸多子系統,系統間為了穩定,程式間多數固定Token+特殊驗證進行調用,且後期還要提供給其他兄弟部門系統共同調用。 原則上:每套系統都必須單獨接入到官方,但官方的接入複雜,還要官方指定機構認證的證書 ...
  • 本文介紹下電腦設備關機的情況下如何通過網路喚醒設備,之前電源S狀態 電腦Power電源狀態- 唐宋元明清2188 - 博客園 (cnblogs.com) 有介紹過遠程喚醒設備,後面這倆天瞭解多了點所以單獨加個隨筆 設備關機的情況下,使用網路喚醒的前提條件: 1. 被喚醒設備需要支持這WakeOnL ...
  • 前言 大家好,推薦一個.NET 8.0 為核心,結合前端 Vue 框架,實現了前後端完全分離的設計理念。它不僅提供了強大的基礎功能支持,如許可權管理、代碼生成器等,還通過採用主流技術和最佳實踐,顯著降低了開發難度,加快了項目交付速度。 如果你需要一個高效的開發解決方案,本框架能幫助大家輕鬆應對挑戰,實 ...