WPF中Binding

WPF中Binding_第1张图片

绑定ViewModel中的数据

添加数据上下文

方法一:在XAML中添加


    

方法二:在界面层的cs文件中添加

this.DataContext = new MainWindowViewModel();

绑定

public string Message { get; set; } = "Hello World";

//简写此一个参数默认是Path

//什么都不屑默认绑定DataContext

绑定资源字典

简单的绑定资源字典的数据


    


    Hello, World


    
    //简写
        
        //绑定动态资源只能这样简写,写完整会报错
        

绑定cs文件中资源字典的数据

先定义一个类

class MyResourece
{
    public string Message { get; } = "Public Property";
    public static string StaticString = "Static String";
    public const string ConstString = "Const String";
}

把类读取到资源字典


    

对于静态,常量,enum,都得用x:Staic来访问,普通的资源可以用StaticResource


//静态和常量得用x:Static访问


绑定控件

ElementName


    
    

x:Reference

当ElementName失效时可以用x:Reference,这是通用什么情况下都可以用

TextBlock Text="{Binding Source={x:Reference Name=txt},Path=Text}" />

RelativeSource


我想读取到tag1的写法,当有多个相同的属性可以用AncestorLevel=3,标识找到父级第三个Grid


    
        
            
        
    

用ReletiveSource绑定同级别控件


    
    

绑定自己的写法四种写法





绑定模板的属性,两种先给发等价


    


    

StringFormat

StringFormat可以指定格式,:F3表示小数点后三位小数


MultiBinding


    
        
            
                
                

            
        
    

有Content属性的控件,可以用ContentStringFormat


    

FallbackValue和TargetNullValue

FallbackValue在没有绑定成功时优先显示

TargetNullValue在绑定的值为空时优先显示

对比

RelativeSource、ElementName、x:Reference中前两者依赖对象树寻找关系,x:Reference可以从文档搜索,前两者绑定失效可以用x:Reference

x:Reference的缺陷,无法绑定自己的父级

BindingProxy

public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

    
    


    

你可能感兴趣的:(WPF,wpf,开发语言)