问题场景:
界面上有个ListBox控件,它的内容Item绑定了一个列表,即 ItemsSource =”{Binding StudentList}”。这个StudentList列表在该界面View对应的ViewModel中赋值。ListBox中每个元素Item都是一个Student实体类对象,核心代码如下:

View:

<ListBox 
    x:Name="studentLB" Margin="0" 
    VerticalAlignment="Top"
    HorizontalAlignment="Left"
    HorizontalContentAlignment="Stretch"
    ScrollViewer.CanContentScroll="False"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    ScrollViewer.VerticalScrollBarVisibility="Visible"
    ItemsSource="{Binding StudentList}">
     <!-- 流式布局,左对齐 -->
     <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
             <WrapPanel HorizontalAlignment="Left"/>
         </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
    <!-- 条目的模板 -->
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Bingding FirstName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ViewModel:

private ObservableCollection<Student> studentList;
public ObservableCollection<Student> StudentList    // 前台ListBox的ItemsSource绑定该列表
    get { return studentList; }
    set { SetProperty(ref studentList, value); }

Student.cs实体类

public Class Student
    public int Id { get; set; } // 唯一标识符
    public string FirstName { get; set; }
    public string LastName { get; set; }

需求:现在条目中TextBlock 绑定的是Student对象的FirstName属性,如何将其改为绑定到LastName属性?

由于ItemsSource绑定到ViewModel中的StudentList列表,在Controller层从服务端获取到列表数据后,先进行加工,再赋值给StudentList。如先用一个临时列表TempList记录服务端返回的数据,然后遍历并修改该列表中的内容,想修改后的内容赋值给StudentList,如下: // 由于前台TextBlock绑定的是FirstName属性,现将FirstName的值改为LastName的值,即保持前台绑定不变的情况下,动态修改被绑定的属性的值。 foreach(Student item in TempList) //sourceList是从服务端获取的列表数据 foreach(Student source in SourceList) if (item.id == source.id) item.FirstName = source.LastName;

经过测试,虽然数据层的确发生了改变,但显示层却并没有更新。说好的MVVM呢?怎么会数据变了不自动更新界面的??

将ListBox的界面改为采用Style样式,准备两种样式,区别仅在于TextBlock绑定到的是FirstName还是LastName。在Controller层动态修改ListBox使用的样式!如可以用一个按钮,每次点击都来回切换这两种样式。

新建样式文件StudentStyle.xaml:

<!-- ListBox样式 切换显示学生的FirstName/LastName -->
<!-- 这两种样式仅有ListBoxItem中的TextBlock绑定到FirstName/LastName的不同 -->
<ResourceDictionary  x:Class="YourProjectName.Presentation.Style.ListBox_StudentStyle"
        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">
    <!-- 样式1:显示FirstName -->
    <Style x:Key="firstNameStyle" TargetType="{x:Type ListBox}">
        <Setter Property="Margin" Value="0"/>
        <Setter Property="ItemsSource" Value="{Binding SpacePlansList}"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="VerticalAlignment" Value="Top"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
        <!-- 流式布局 左对齐 -->
        <Setter Property="ListBox.ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel HorizontalAlignment="Left"/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ListBox.ItemTemplate">
              <Setter.Value>
                  <DataTemplate>
                      <TextBlock Text="{Binding FirstName}"/>
                  </DataTemplate>
              </Setter.Value>
          </Setter>
      </Style>
      <!-- 样式2:显示LastName -->
      <Style x:Key="lastNameStyle" TargetType="{x:Type ListBox}">
          <Setter Property="Margin" Value="0"/>
          <Setter Property="ItemsSource" Value="{Binding SpacePlansList}"/>
          <Setter Property="BorderThickness" Value="0"/>
          <Setter Property="VerticalAlignment" Value="Top"/>
          <Setter Property="HorizontalAlignment" Value="Left"/>
          <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
          <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
          <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
          <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
          <!-- 流式布局 左对齐 -->
          <Setter Property="ListBox.ItemsPanel">
              <Setter.Value>
                  <ItemsPanelTemplate>
                      <WrapPanel HorizontalAlignment="Left"/>
                  </ItemsPanelTemplate>
              </Setter.Value>
          </Setter>
          <Setter Property="ListBox.ItemTemplate">
              <Setter.Value>
                  <DataTemplate>
                      <TextBlock Text="{Binding LastName}"/>
                  </DataTemplate>
              </Setter.Value>
          </Setter>
      </Style>
</ResourceDictionary>

View:

<!-- 引入样式资源 -->
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Presentation/Style/ListBox_StudentStyle.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
<!-- 使用样式,默认使用显示FirstName的样式 -->
<ListBox x:Name="studentLB" Style="{StaticResource firstNameStyle}"/>

控制层动态修改ListBox的样式:

private Style listbox_FirstNameSytle;   // 显示FirstName的样式
private Style listbox_LastNameSytle;    // 显示LastName的样式
// 在控制层的初始化方法中,获取这两种样式
public void Initialize()
    var listBoxStyle = new ResourceDictionary
        Source = new Uri("/YourProjectName;component/Presentation/Style/ListBox_StudentStyle.xaml", UriKind.RelativeOrAbsolute) // 指定样式文件的路径
    listbox_FirstNameSytle = listBoxStyle["firstNameStyle"] as Style;
    listbox_LastNameSytle = listBoxStyle["lastNameStyle"] as Style;
private void btn_Click(object sender, RoutedEventArgs e)
    // 根据按钮的状态,切换ListBox的样式
    if (view.btn.IsChecked == true)
        view.studentLB.Sytle = listbox_LastNameSytle;
        view.studentLB.Sytle = listbox_FirstNameSytle;

经测试,该方法可行!

准备多套样式,通过动态修改样式来实现类似于动态修改绑定的效果。

WPF MVVM模式下使用 RichTextBox并使滚动条滚动到文本的末尾 1、创建RichTextBox的依赖属性RichText public class RichTextBoxHelper : DependencyObject public static string GetRichText(DependencyObject obj) return (string)obj.GetValue(RichTextProperty);
WPF-BingdingMVVM Bingding一种Xaml与其对应cs后台数据交互方式,该模式下后台修改数据会直接呈现在前台显示,即所谓的数据驱动UI; MVVM一种Bingding模式,因为其把Model和View隔离而被推荐使用; Bingding主要有三种方式:变量直接绑定、MVVM模式绑定、MVVM模式集合绑定,这三种绑定模式可以混合使用; 至于MVVM是好是坏不做讨论,至少有一...
WPF是微软继MFC之后推出的界面框架,标签语言XAML(读作zaml)在Windows窗体应用程序开发中,与BS结构中的与HTML+CSS+Javascript作用一样。这类标签语言的好处就是可以很轻松的和后台逻辑代码解耦和。 XAML在.NET框架当中的位置: 由于XAML被设计用来专门编写Windows窗口程序的,与BS架构区分客户端和服务器端不同,所以与HTML在浏览器上被解析不...
wpf中使用stylewpfstyleSetterTriggermultitriggerDataTriggerMultiDataTriggerEventTrigger代码示例代码下载地址 wpfstyle 构成style最重要的两种元素: setter 和trigger setter类帮助我们设置控件的静态外观风格,Trigger类帮助我们设置控件的行为风格 Setter setter 类的Property属性用来指明你想为目标的哪个属性赋值;Setter类的Value属性则是你提供的属性值。如果在wi
WPF MVVM下交互式委托笔记@WPF WPFMVVM架构下的窗体与窗体间的互动 WPF中的Window与Window之间在普通的后台调用情况下,实现交互的方式比较简单,但是,在MVVM的架构下,需要适当做一些调整,这里做下简单的示例,做个记录保存,可以的话供下参考或者理解。 1-ParentWin与ChildWin //ParentWin内声明ChildWin //声明后调用显示 Window ChildWin=new Window(); ChildWin.ShowDialog(); 2-MVVM
1.实现INotifyPropertyChanged接口 ViewModel类实现INotifyPropertyChanged接口,并实现: public event PropertyChangedEventHandler PropertyChanged; 属性变化时事件 2.属性在更改时,在访问器中调用触发事件 private string _name; public string Name return _name; 在wpf中,所有支持绑定的属性本质上都是封装后的依赖属性,也就是说,只有依赖属性才可以进行绑定 下面演示了在Button按钮上为Content属性设置了一个绑定语法, 如下所示: <Button Content="{Binding Content}"/> 当你在Content属性按下F12转到定义时,可以观察到Button按钮所继承的类的定义,如下所示: 如图上红圈位置, 定义了一个静态的只读字段ContentProperty。 通过查看该字段的类型DependencyProperty Component_name.SetResourceReference(StyleProperty, "LabelSuccess"); 以上表示将一个Label的Style改为DynamicResource LabelSuccess 相似的,还可以改为LabelWarning等形式:
最近有个奇怪的需求,希望能动态修改DataTrigger,试了一下,没做出来,最后是通过新建了额外的一个Style解决,记录如下,希望在DataTrigger里面动态增加一个Trigger。 &lt;Style TargetType="{x:Type ContentControl}" x:Key="mainContentAStyle"&gt; &lt;Style.Trigger...
首先看一下窗口的xaml文档 <Window x:Class="WpfApp1_test.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/bl