实现WPF界面控件属性与后台数据属性绑定。
建立解决方案如下:
MainWindow添加
一个ListView,显示List,添加绑定语句: ItemsSource="{Binding Test}“。
两个Button,增加List和清空List。
xaml代码如下:
1 <Window x:Class="TESTBind.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <Grid> 6 <ListView Height="100" HorizontalAlignment="Left" Margin="12,39,0,0" Name="listView1" VerticalAlignment="Top" Width="481" 7 ItemsSource="{Binding Test}"/> 8 <Button Content="List++" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 9 <Button Content="ClearList" Height="23" HorizontalAlignment="Left" Margin="124,12,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" /> 10 </Grid> 11 </Window>
添加BindModel,定义需要绑定的变量
添加Microsoft.Practices.Prism.dll库,引用using Microsoft.Practices.Prism.ViewModel;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Microsoft.Practices.Prism.ViewModel; namespace TESTBind.Models { public class BindModel : NotificationObject { public BindModel() { test = new ObservableCollection<string>(); } private ObservableCollection<string> test; public ObservableCollection<string> Test { get { return test; } set { test = value; this.RaisePropertyChanged("Test"); } } } }
为Test赋值,bindModel.Test = new ObservableCollection<string>(testList);
这里ObservableCollection提供数据更新,我之前用过List,但是只能更新一次,当绑定值第二次改变时,程序就会报错。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Data; 8 using System.Windows.Documents; 9 using System.Windows.Input; 10 using System.Windows.Media; 11 using System.Windows.Media.Imaging; 12 using System.Windows.Navigation; 13 using System.Windows.Shapes; 14 using TESTBind.Models; 15 using System.Collections.ObjectModel; 16 17 namespace TESTBind 18 { 19 /// <summary> 20 /// MainWindow.xaml 的交互逻辑 21 /// </summary> 22 public partial class MainWindow : Window 23 { 24 public MainWindow() 25 { 26 InitializeComponent(); 27 Init(); 28 } 29 private void Init() 30 { 31 listNum = 1; 32 testList = new List<string>(); 33 bindModel = new BindModel(); 34 this.DataContext = bindModel; 35 } 36 private void button1_Click(object sender, RoutedEventArgs e) 37 { 38 testList.Add("WPF界面绑定" + listNum); 39 bindModel.Test = new ObservableCollection<string>(testList); 40 listNum++; 41 } 42 private int listNum; 43 private List<string> testList; 44 private BindModel bindModel; 45 46 private void button2_Click(object sender, RoutedEventArgs e) 47 { 48 testList.Clear(); 49 bindModel.Test = new ObservableCollection<string>(testList); 50 listNum = 1; 51 } 52 } 53 }
时间: 2024-10-07 04:06:27