MVVM模式里面用户UI界面的数据返回问题,让我纠结了好几天,一直得不到数据,今天总算能取到UI界面的数据了!
我采用的是ListView显示数据和Prism模式,并且将数据显示成了大图标的样式,即水平显示,但是下面测试用的我就没有采用水平显示,做了简单Model。
XAML 代码:
<ListView ItemsSource="{Binding ProductList}" x:Name="lv" Margin="8,8,8,37.96" SelectedItem="{Binding CurrentSelected, Mode=TwoWay}" > <ListView.View> <GridView x:Name="datagrid"> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}"/> </GridView> </ListView.View> <!-定义了触发命令-> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <!-调用xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"-> <i:InvokeCommandAction Command="{Binding SelectMenuCommand}" CommandParameter="{Binding CurrentSelected,ElementName=lv}"/> </i:EventTrigger> </i:Interaction.Triggers> </ListView> <Label Content="{Binding CurrentSelected.Price}" HorizontalAlignment="Left" Margin="34,289,0,0" VerticalAlignment="Top" Width="312"/>
这里绑定的数据必须是同数据类型才能在,SelectedItem里面返回到后台的VM里面,用户数据返回的时候必须是TwoWay,不然,无法在后台得到值。
VM 代码:
public DelegateCommand SelectMenuCommand { get; set; } ObservableCollection<TestModel> m_lstProducts = new ObservableCollection<TestModel>(); public MainWindowVM() { m_lstProducts.Add(new TestModel() { Name = "Car", Price = 1 }); m_lstProducts.Add(new TestModel() { Name = "Pencil", Price = 2 }); m_lstProducts.Add(new TestModel() { Name = "Computer", Price = 3 }); m_lstProducts.Add(new TestModel() { Name = "Table", Price = 4 }); m_lstProducts.Add(new TestModel() { Name = "Chair", Price = 5 }); } public ObservableCollection<TestModel> ProductList { get { return m_lstProducts; } } private TestModel currentselected; public TestModel CurrentSelected { get { return currentselected; } set { if (currentselected != value) { currentselected = value; this.RaisePropertyChanged("CurrentSelected"); } } } }
这里 简化了 MODEL数据,数据模型里面 只有名字和价格。
这里 要注意的就是 绑定在SelectedItem上面的类型必须是M,我就是搞了几天,搞的稀里糊涂的,今天总算把这个理清了,写出来给自己做个记录。
时间: 2024-10-21 13:02:14