首页 > 其他分享 >WPF.Basic.数据绑定

WPF.Basic.数据绑定

时间:2023-05-20 16:56:10浏览次数:43  
标签:Windows 绑定 System Hello Basic using WPF public

WPF常用五种数据绑定方式

  绑定方式一(绑定元素依赖属性)

<StackPanel>
    <Slider Name="s1" Value="10" Maximum="100"></Slider>
  
    <TextBlock FontSize="{Binding ElementName=s1,Path=Value}" Text="看着我" ></TextBlock>
</StackPanel>

  绑定方式二(绑定RelativeSources)

  第一种关系: Self

<TextBlock FontSize="18" FontWeight="Bold" Margin="10" 
Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>

第二种关系:TemplatedParent

<Style TargetType="{x:Type Button}"><Setter Property="Background" Value="Green"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Button}"><Grid><Ellipse><Ellipse.Fill><SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
</Style>

第三种关系:AncestorType

<Grid><Label Background = {Binding Path=Background, RelativeSource={RelativeSource FindAncestor   AncestorType={x:Type Grid}}}/>
</Grid>

绑定方式三(StaticResource静态资源/DynamicResource动态资源)

 

<Window.Resources>     
        <sys:String x:Key="Content" >
           Hello World!
        </sys:String>
    </Window.Resources>
    <Grid>
        <WrapPanel>
            <TextBlock Text="静态"/>
            <TextBox Text="{StaticResource Content}" Width="100" x:Name="TextBox1"/>
            <TextBlock Text="动态" Margin="10,0,0,0"/>
            <TextBox Text="{DynamicResource Content}" Width="100" x:Name="TextBox2"/>
            <Button Content="改变资源值" Click="ChangeBtn_Click" Width="100"/>       
        </WrapPanel>
    </Grid>

 

CS代码

private void ChangeBtn_Click(object sender, RoutedEventArgs e)
  {
      this.Resources["Content"] = "内容变了";
  } 

不管是动态资源还是静态资源,都需要现在资源里定义好"X:Name"资源扩展标记"资源字典"比如<sys:String x:Key="Content" > Hello World! </sys:String>

绑定方式四(绑定到集合元素 ItemSource)

 XAML代码

 

        <Border Grid.Row="2" Grid.Column="3">
            <ListBox
                x:Name="todoList"
                HorizontalContentAlignment="Stretch"
                ItemsSource="{Binding VarList}"
                ScrollViewer.VerticalScrollBarVisibility="Hidden">

                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <DockPanel MaxHeight="80" LastChildFill="False">
                            <ToggleButton DockPanel.Dock="Right" />
                            <StackPanel>
                                <TextBlock
                                    FontSize="16"
                                    FontWeight="Bold"
                                    Text="{Binding Name}" />
                                <TextBlock
                                    Margin="0,5"
                                    Opacity="0.5"
                                    Text="{Binding Value}" />
                                <TextBlock
                                    Margin="0,5"
                                    Opacity="0.5"
                                    Text="{Binding Description}" />
                                <TextBlock
                                    Margin="0,5"
                                    Opacity="0.5"
                                    Text="{Binding InsertTime}" />
                            </StackPanel>
                        </DockPanel>

                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Border>

 

  CS代码

 

        public ReportDataViewModel()
        {
            VarList.Add(new ActualData() { Description = "浮点数1", Name = "Float1", InsertTime = DateTime.Now, Value = CommonMethods.CurrentPLCValue["Float1"] });
            VarList.Add(new ActualData() { Description = "浮点数2", Name = "Float2", InsertTime = DateTime.Now, Value = CommonMethods.CurrentPLCValue["Float2"] });
            VarList.Add(new ActualData() { Description = "浮点数3", Name = "Float3", InsertTime = DateTime.Now, Value = CommonMethods.CurrentPLCValue["Float3"] });
            VarList.Add(new ActualData() { Description = "浮点数4", Name = "Float4", InsertTime = DateTime.Now, Value = CommonMethods.CurrentPLCValue["Float4"] });
        }


        private ObservableCollection<ActualData> varList = new ObservableCollection<ActualData>();

        public ObservableCollection<ActualData> VarList
        {
            get { return varList; }
            set { varList = value; }
        }

 

绑定方式五(DataContext)(最常规的绑定)

 XAML代码

 

 1 <Window x:Class="MyWPFSimple5.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:MyWPFSimple5"
 7         mc:Ignorable="d" DataContext="{Binding Source={StaticResource vmLocator}, Path=HelloObj}"
 8         Title="MainWindow" Height="250" Width="400">
 9     <Grid>
10         <StackPanel>
11             <TextBox Text="{Binding Say}" BorderBrush="Black" Margin="10"/>
12             <Button Content="改变内容" Click="Button_Click" Margin="10"/>
13         </StackPanel>
14     </Grid>
15 </Window>

 

  CS代码

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using System.Windows;
 8 using System.Windows.Controls;
 9 using System.Windows.Data;
10 using System.Windows.Documents;
11 using System.Windows.Input;
12 using System.Windows.Media;
13 using System.Windows.Media.Imaging;
14 using System.Windows.Navigation;
15 using System.Windows.Shapes;
16 
17 namespace MyWPFSimple5
18 {
19     /// <summary>
20     /// MainWindow.xaml 的交互逻辑
21     /// </summary>
22     public partial class MainWindow : Window
23     {
24         public MainWindow()
25         {
26             InitializeComponent();
27         }
28 
29         private void Button_Click(object sender, RoutedEventArgs e)
30         {
31             Hello hello = DataContext as Hello;
32             hello.Say += "+1";
33         }
34     }
35 
36     public class Locator
37     {
38         public Locator()
39         {
40             //HelloObj = new Hello();
41         }
42 
43         private Hello m_HelloObj;
44         public Hello HelloObj
45         {
46             get
47             {
48                 if (m_HelloObj == null)
49                 {
50                     m_HelloObj = new Hello();
51                 }
52                 return m_HelloObj;
53             }
54             set
55             {
56                 m_HelloObj = value;
57             }
58         }
59     }
60 
61     public class Hello : INotifyPropertyChanged
62     {
63         public Hello()
64         {
65             Say = "Hello World!";
66         }
67         private string m_Say;
68         public string Say { get { return m_Say; } set { m_Say = value; RaisedPropertyChanged(nameof(Say)); } }
69 
70         public event PropertyChangedEventHandler PropertyChanged;
71         protected virtual void RaisedPropertyChanged(string name)
72         {
73             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
74         }
75     }
76 }

 

标签:Windows,绑定,System,Hello,Basic,using,WPF,public
From: https://www.cnblogs.com/HomeSapiens/p/17417443.html

相关文章

  • WPF.Basic.依赖属性
    1依赖属性定义  在WPF界面的数据绑定中,为了能够使绑定源数据和绑定目标在变更后能够通知对方,.net在原来的属性之上设计了依赖属性    所以支持绑定的属性本质上它都是封装后的依赖属性。那么也就是说,只有依赖属性才可以进行绑定。  1依赖属性使用publiccl......
  • ORACLE数据库获取SQL绑定变量值
    文档课题:ORACLE数据库获取SQL绑定变量值.数据库:oracle11.2.0.41、查v$sql视图1.1、理论知识v$sql视图中字段BIND_DATA存储绑定变量值,但从该视图查询存在很大局限性,其记录频率受_cursor_bind_capture_interval隐含参数控制,默认值为900,即每900秒记录一次绑定值,意味着900内绑定变......
  • wpf XAML 设计器异常,提示NullReferenceException 未将对象引用设置到对象
     在cs构造函数里手动注册,并且在控件的构造函数里增加判断if(DesignerProperties.GetIsInDesignMode(this)){return;}//在这里才注册Load事件cmbSpeed.Loaded+=cmbSpeed_Loaded;来源:https://www.cnblogs.com/zsx-blog/p/8311633.html ......
  • C# WPF 实现高频量化,自动运行。
    基于交易所编写的量化交易程序。由WPF和C#实现。改进版。再也不用时时刻刻盯盘了。 并非上图的思路所编写,仅供参考,思路由个人的想法异同。仅仅个人用途。不做商业用途。如下图所示,会在任务栏实时刷新价格,也可以mini窗口显示。由于存储限制,用了灰色的gif演示。都是现货的思路......
  • WPF单进程实例
    用互斥量Mutex实现如果已经存在Mutex,则会创建失败。注意:Mutex要声明成全局的,不能是局部变量,否则会判断失败。 重写Startup函数,加上单例判断。参考下面代码:1publicpartialclassApp:Application2{3System.Threading.Mutexmutex;45......
  • 从桌面端到移动端,.NET MAUI为什么对WPF开发人员更简单?
    .NET多平台应用程序UI(.NETMAUI)的市场吸引力与日俱增,这是微软最新的开发平台,允许开发者使用单个代码库创建跨平台应用程序。尽管很多WPF开发人员还没有跟上.NETMAUI的潮流,但我们将在这篇文章中为大家展示他的潜力,具体来说想描述一下WPF和.NETMAUI之前的共性。PS:DevExpressWP......
  • WPF.Basic.样式基础(一)
    WPF的样式总的来说有两种使用方式1.全局样式1.1在Windows.Resources下定义全局样式,当然Style作为一种资源,也可以在其他的地方定义资源(当没有X:KEY(扩展标记)值的时候就是对TargetType都有用,无语targetType绑定资源)1<Windows.Resources>2<Stylex:Key="Buttonstyle......
  • WPF 异步加载数据,窗体事件
    加载WPF界面时,需要获取数据,而数据返回的时间比较长,这个时候可以异步加载数据到界面。 1、首先在XAML中触发窗口载入事件 2、在后台代码中处理窗口载入事件(1)找到主窗口类 (2)在MainWindow类中添加XAML中加入的窗口载入事件 这个事件中可以放置各种界面预处理代码 n......
  • WPF.Basic.ICommand使用
    WPF命令绑定的各种方式引言在WPF开发过程中,不得不学习的就是MVVM模式。但是在MVVM中又绕不开命令(Command)的使用。下面通过几种方式介绍我了解的WPF命令绑定方式。如何使用控件继承ICommand接口,直接使用Command首先通过这里简单介绍Command在MVVM中的使用。ViewModel类......
  • c-for-go cgo 绑定自动生成工具
    c-for-go可以快速的生成cgo绑定代码的工具,目前有不少golang项目使用了此工具,比如cloudflare/ipvs也使用了此工具参考处理 参考使用这个是libvpx的一个项目yaml定义文件---GENERATOR:PackageName:vpxPackageDescription:"Packagevpxpro......