WPF例7-動態(tài)控件修改綁定的列表數(shù)據(jù)

一知举、由DataTemplate生成的列表因?yàn)闆]有了Name屬性瞬沦,從而不能直接訪問觸發(fā)事件的控件,所以要通過e.OriginalSource拿到控件對象雇锡,從而更改綁定到控件的數(shù)據(jù)逛钻。

MainWindow.xaml.cs文件代碼(按鍵盤→鍵可以看到右側(cè)被擋住的代碼)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public Studnets students { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            students = new Studnets();
            //添加幾條數(shù)據(jù)
            students.Add(new Student { IsGood = false, Name = "Tom", Age=18 });
            students.Add(new Student { IsGood = false, Name = "Peter", Age=20 });
            students.Add(new Student { IsGood = true, Name = "Hank", Age=23 });
            students.Add(new Student { IsGood = false, Name = "Nancy", Age=30 });
            students.Add(new Student { IsGood = true, Name = "Joe", Age=12 });
            DataContext = this; //設(shè)置窗口數(shù)據(jù)上下文為當(dāng)前對象,ListBox控件會自動查找到students集合屬性
        }

        //事件處理函數(shù):找到按鈕所在行锰提,修改對應(yīng)的Age屬性
        private void ListBox_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;//查找到單擊的按鈕
            var cp = btn.TemplatedParent as ContentPresenter;//查找到動態(tài)生成的單行ContentPresenter對象
            Student student = cp.Content as Student;//查找到ContentPresenter對象的數(shù)據(jù)
            student.Age += 1;//更改數(shù)據(jù)
        }
    }
    //數(shù)據(jù)類
    public class Student:DependencyObject
    {
        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Name.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty NameProperty =
            DependencyProperty.Register("Name", typeof(string), typeof(Student));


        public bool IsGood
        {
            get { return (bool)GetValue(IsGoodProperty); }
            set { SetValue(IsGoodProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsGood.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsGoodProperty =
            DependencyProperty.Register("IsGood", typeof(bool), typeof(Student));


        public int Age
        {
            get { return (int)GetValue(AgeProperty); }
            set { SetValue(AgeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Age.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AgeProperty =
            DependencyProperty.Register("Age", typeof(int), typeof(Student));


    }
    public class Studnets : ObservableCollection<Student> { }
    public class BoolToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? Brushes.Green : Brushes.Red;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

MainWindow.xaml文件代碼(按鍵盤→鍵可以看到右側(cè)被擋住的代碼)

<Window x:Class="WpfApp3.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:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ResourceDictionary>
            <local:BoolToBrushConverter x:Key="BoolToBrushConverter"/>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding students}" HorizontalAlignment="Left" 
                 Height="271" Margin="22,26,0,0" VerticalAlignment="Top" Width="332"
                 ButtonBase.Click="ListBox_Click">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <StackPanel Orientation="Horizontal">
                            <Label Content="{Binding Name}" Width="100"/>
                            <Rectangle Width="10" Height="10" Margin="5" Fill="{Binding IsGood, Converter={StaticResource BoolToBrushConverter}}"/>
                            <Label Content="{Binding Age}" Width="50"/>
                            <Button Content="增加一歲" Width="50"/>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

代碼效果如下:


代碼效果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末曙痘,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子立肘,更是在濱河造成了極大的恐慌边坤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谅年,死亡現(xiàn)場離奇詭異茧痒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)融蹂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門旺订,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人超燃,你說我怎么就攤上這事区拳。” “怎么了意乓?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵樱调,是天一觀的道長。 經(jīng)常有香客問我洽瞬,道長本涕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任伙窃,我火速辦了婚禮,結(jié)果婚禮上样漆,老公的妹妹穿的比我還像新娘为障。我一直安慰自己,他們只是感情好放祟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布鳍怨。 她就那樣靜靜地躺著,像睡著了一般跪妥。 火紅的嫁衣襯著肌膚如雪鞋喇。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天眉撵,我揣著相機(jī)與錄音侦香,去河邊找鬼落塑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛罐韩,可吹牛的內(nèi)容都是我干的憾赁。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼散吵,長吁一口氣:“原來是場噩夢啊……” “哼龙考!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起矾睦,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤晦款,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后枚冗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體柬赐,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年官紫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了肛宋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,001評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡束世,死狀恐怖酝陈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情毁涉,我是刑警寧澤沉帮,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站贫堰,受9級特大地震影響穆壕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜其屏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一喇勋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧偎行,春花似錦川背、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至妙真,卻和暖如春缴允,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背珍德。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工练般, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留矗漾,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓踢俄,卻偏偏與公主長得像缩功,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子都办,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評論 2 355