首页 > 其他分享 >WPF 绑定

WPF 绑定

时间:2024-08-16 17:31:12浏览次数:6  
标签:case object return 绑定 value WPF public

绑定就是Binding,是控件和数据之间交互的类。

source = {binding}

source = {binding RelativeSource={RelativeSource self},Path=DataContext}

效果相同。

例如:直接绑定数据源

前台xaml界面

    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Number}" Width="50" Height="30" Background="WhiteSmoke" Foreground="Black"/>
            <TextBlock Text="{Binding Name}" Width="50" Height="30" Background="WhiteSmoke" Foreground="Black"/>
            <TextBlock Text="{Binding Class}" Width="50" Height="30" Background="WhiteSmoke" Foreground="Black"/>
        </StackPanel>
 </Grid>
    public partial class MainWindow : Window
    {
        public class StudentInfo
        {
            public int Number { get; set; }
            public string Name { get; set; }
            public string Class { get; set; }
        }
        public MainWindow()
        {
            InitializeComponent();
            List<StudentInfo> list = new List<StudentInfo>();
            for (int i = 0; i < 10; i++)
            {
                StudentInfo entity1 = new StudentInfo();
                entity1.Number = i;
                entity1.Name = "其他" + i;
                entity1.Class = "其他" + i + "其他";
                list.Add(entity1);
            }
            this.DataContext = list;
        }
    }

这里最重要的是this.DataContext = list; 不同的时候DataContext 是不一样的

其中RelativeSource有4种模式:

1.RelativeSource Mode=Self,绑定自身的值。

2.RelativeSource Mode=PreviousData,么看懂,反正就是最后一行数据少了(***),图如下

3.TemplatedParent模式,绑定一个模板。

4.FindAncestor模式,绑定特定的类型。

绑定有三种,Binding,PriorityBinding,MultiBinding。

第一种,Binding,单个值绑定

2个控件一旦进行绑定,那么2个控件是相互的,你变化,我也跟着变化。

1.当绑定写在第一个控件上

 

<StackPanel>
            <Slider x:Name="s" Value="{Binding ElementName=t, Path=Text}"></Slider>
            <TextBox x:Name="t" Text="0"></TextBox>
 
            <!--<Slider x:Name="s" Value="0"></Slider>
            <TextBox x:Name="t" Text="{Binding ElementName=s, Path=Value,UpdateSourceTrigger=PropertyChanged}"></TextBox>-->
        </StackPanel>
2.当绑定写在第二个控件上
 <StackPanel>
            <!--<Slider x:Name="s" Value="{Binding ElementName=t, Path=Text}"></Slider>
            <TextBox x:Name="t" Text="0"></TextBox>-->
 
            <Slider x:Name="s" Value="0"></Slider>
            <TextBox x:Name="t" Text="{Binding ElementName=s, Path=Value,UpdateSourceTrigger=PropertyChanged}"></TextBox>
        </StackPanel>

<Window x:Class="Dispatcher.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:Dispatcher" xmlns:collection="clr-namespace:System.Collections;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:AsyncDataSource x:Key="AsyncDS" SlowestDP="最慢" SlowerDP="慢" FastDP="快"  />
    </Window.Resources>
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" DataContext="{Binding Source={StaticResource AsyncDS}}">
            <TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">Priority Binding</TextBlock>
            <TextBlock Background="Honeydew" Width="100" HorizontalAlignment="Center">
                <TextBlock.Text>
                    <PriorityBinding FallbackValue="defaultvalue">
                        <Binding Path="SlowestDP" IsAsync="True"/>
                        <Binding Path="SlowerDP" IsAsync="True"/>
                        <Binding Path="FastDP" />
                    </PriorityBinding>
                </TextBlock.Text>
            </TextBlock>
        </StackPanel>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Dispatcher
{
    public class AsyncDataSource
    {
        private string _fastDP;
        private string _slowerDP;
        private string _slowestDP;
 
        public AsyncDataSource()
        {
        }
 
        public string FastDP
        {
            get { return _fastDP; }
            set { _fastDP = value; }
        }
 
        public string SlowerDP
        {
            get
            {
                Thread.Sleep(3000); //模拟耗时
                return _slowerDP;
            }
            set { _slowerDP = value; }
        }
 
        public string SlowestDP
        {
            get
            {
                Thread.Sleep(5000); //模拟耗时
                return _slowestDP;
            }
            set { _slowestDP = value; }
        }
    }
}

第三种,MultiBinding

值转换分为单值转换IValueConverter和多值转换IMultiValueConverter。

使用值转化类可以简单轻松的解决前台界面显示数据的变化,解决同一种数据多种表示的难题。

一、单值转换IValueConverter

1.首先建立一个转换类,引用using System.Windows.Data;,然后继承IValueConverter,点击实现接口

    class YesNoToConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //value就是前台传递过来的值
            switch (value.ToString().ToLower())
            {
                case "y":
                case "ye":
                case "yes":
                    return true;
                case "n":
                case "no":
                case "non":
                    return false;
            }
            return false;
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool)
            {
                if ((bool)value == true)
                    return "yes";
                else
                    return "no";
            }
            return "no";
        }
    }
<Window x:Class="WpfApp2.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:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:YesNoToConverter x:Key="yn"/>
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBox Name="txtValue" />
        <WrapPanel Margin="0,10">
            <TextBlock Text="Current value is: " />
            <TextBlock Name="YN" Text="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource yn}}"></TextBlock>
        </WrapPanel>
        <CheckBox IsChecked="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource yn}}" Content="{Binding ElementName=YN,Path=Text}" />
    </StackPanel>
</Window>

二、多值转换IMultiValueConverter 

1.首先建立一个转换类,引用using System.Windows.Data;

   class YesNoToConverter2 : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //这里的values就是多个值,与前台绑定的数据有关,有几个值,就判断几个值
            if (values == null || values.Length < 2)
                return DependencyProperty.UnsetValue;
            double verValue = (double)values[0];
            double horValue = (double)values[1];
            if (verValue > horValue)
                return new SolidColorBrush(Colors.Green);
            else if (verValue < horValue)
                return new SolidColorBrush(Colors.Red);
            return new SolidColorBrush(Colors.Yellow);
        }
 
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
<Window x:Class="WpfApp2.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:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:YesNoToConverter2 x:Key="cvtColor"/>
    </Window.Resources>
    <Grid>
        <Label x:Name="label" Content="纵向值:" HorizontalAlignment="Left" Margin="10,40,0,0" VerticalAlignment="Top"/>
        <Label x:Name="label1" Content="横向值:" HorizontalAlignment="Left" Margin="10,80,0,0" VerticalAlignment="Top"/>
        <Slider x:Name="sliderVer" HorizontalAlignment="Left" Margin="75,43,0,0" VerticalAlignment="Top" Width="192"/>
        <Slider x:Name="sliderHor" HorizontalAlignment="Left" Margin="75,81,0,0" VerticalAlignment="Top" Width="192"/>
        <Ellipse   HorizontalAlignment="Left" Height="100" Margin="75,120,0,0" Stroke="Black" VerticalAlignment="Top" Width="100">
            <Ellipse.Fill>
                <MultiBinding Converter="{StaticResource cvtColor}">
                    <Binding Path="Value" ElementName="sliderVer"/>
                    <Binding Path="Value" ElementName="sliderHor"/>
                </MultiBinding>
            </Ellipse.Fill>
        </Ellipse>
    </Grid>
</Window>

拓展:

多值绑定,根据Select下拉框的值来改变Name中背景颜色。

其中,Name和Select都要有属性通知,多值绑定

Select下拉框需要进行事件绑定数据

 <TextBox Style="{StaticResource dgTextBox}"   
                                     Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}">
                                <TextBox.Background>
                                    <MultiBinding  Converter="{StaticResource relayIPColorConverter}">
                                        <Binding Path="Name" />
                                        <Binding Path="Select"  />
                                    </MultiBinding>
                                </TextBox.Background>
                            </TextBox>  

 private void ComboBox_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
        {
            var current = ((sender as ComboBox).DataContext) as StudentInfo;
            switch (((ContentControl)e.AddedItems[0]).Content)
            {
                case "a": current.Type = 1; break;
                case "b": current.Type = 2; break;
                case "c": current.Type = 3; break;
            }
        }
来源:https://blog.csdn.net/u012563853/article/details/124874725

 

标签:case,object,return,绑定,value,WPF,public
From: https://www.cnblogs.com/ywtssydm/p/18363298

相关文章

  • WPF Animation 动画变化值的监控
    WPF动画XXXAnimation即关键类继承制AnimationBase的动画类线性插值动画主要属性FromToDurationAcceleratorDecceleratorFillBehavior等这些常用属性里不做介绍,主要介绍一下几个故事板属性,以备忘记.名称说明Completed动画到达终点时触发,该事件中可以......
  • WPF 触发器
    一、样式触发器样式触发器可以在指定的控件属性满足某种条件后进行一些样式的变换,当触发条件不满足时恢复原样。样式触发器的简单使用<Window.Resources><Stylex:Key="checkBoxStyle"TargetType="CheckBox"><Style.Triggers><TriggerProperty="......
  • 从供应商深度绑定,到走向真正的云原生,他们是这样做的
    供应商深度绑定带来的问题茶百道,这家以创新精神打造新零售模式的企业,在奶茶市场中展现出了卓越的成长势头。面对激烈的市场竞争,公司认识到其成功的关键在于快速响应市场变化,及时迭代产品与服务,因此对研发的敏捷性和效率抱有极高的期待。在早期阶段,受制于研发团队的有限规模,茶百......
  • 从供应商深度绑定,到走向真正的云原生,他们是这样做的
    供应商深度绑定带来的问题茶百道,这家以创新精神打造新零售模式的企业,在奶茶市场中展现出了卓越的成长势头。面对激烈的市场竞争,公司认识到其成功的关键在于快速响应市场变化,及时迭代产品与服务,因此对研发的敏捷性和效率抱有极高的期待。在早期阶段,受制于研发团队的有限规模,茶百......
  • WPF 窗体关闭的方式
    1.Close();关闭当前窗口在WPF应用程序的关闭是有ShutdownMode属性设置,具有3中枚举类型的值:1)OnLastWindowClose(默认值)---应用程序最后一个窗体关闭时关闭应用程序2)OnMainWindowClose---应用程序主窗体关闭时关闭应用程序3)OnxplicitShutdown---显示调用关闭这......
  • C# WindowForm界面初探,窗体访问,绑定数据源,重载构造函数
    今日份主要内容C#WindowForm界面初探Winform项目模板,目录解析窗体对象控件对象界面设计基础1.控件?控件的本质是类,控件是构建用户界面(UserInterface)的基础,通过控件组合设计出符合需求的界面效果。相当于html的标签。基本要求:界面效果,布局交互(事件,委托)2.学习控件......
  • WPF KeyDown MVVM Via Behavior
    <behavior:Interaction.Triggers><behavior:EventTriggerEventName="KeyDown"><behavior:CallMethodActionMethodName="Window_KeyDown"TargetObject="{Binding}"/></behavior:EventTrigger>......
  • WPF Customize control
    //xaml<UserControlx:Class="WpfApp246.EllipseTbk"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc=&q......
  • SLF4J: Class path contains multiple SLF4J bindings. 运行报错 表示在您的应用程序
    java使用SLF4J时出现下面的错误,是因为项目中使用了多个SLF4J的类库SLF4J:ClasspathcontainsmultipleSLF4Jbindings.SLF4J:Foundbindingin[jar:file:/D:/%e5%bd%93%e5%89%8d%e5%b7%a5%e4%bd%9c/SipPBX%e8%ae%af%e6%97%b6/JoinCallOMCC/JoinCallOMCC/out/artifacts/......
  • vue表单输入绑定
    使用v-model指令实现双向数据绑定的集合v-model是v-on和v-bind指令的语法糖(指令集合)可以使用v-model指令在表单input、textarea、select等元素上创建双向数据绑定,他会根据控件类型自动选取正确的方法来更新元素。加上v-model后,只要视图的数据发生了改变,那么vm中的model层的......