WPF 静态资源的方式绑定DataContext

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

这样的方式比用代码直接赋值有个好处,那就是能个实时的显示绑定效果。IDE 还可以提示和 F12 进行跳转定位。

WPF 静态资源的方式绑定DataContext_xml

XAML:

<Window x:Class="MyWPFSimple5.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:MyWPFSimple5"
mc:Ignorable="d" DataContext="{Binding Source={StaticResource vmLocator}, Path=HelloObj}"
Title="MainWindow" Height="250" Width="400">
<Grid>
<StackPanel>
<TextBox Text="{Binding Say}" BorderBrush="Black" Margin="10"/>
<Button Content="改变内容" Click="Button_Click" Margin="10"/>
</StackPanel>
</Grid>
</Window>

Behind Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyWPFSimple5
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Hello hello = DataContext as Hello;
hello.Say += "+1";
}
}

public class Locator
{
public Locator()
{
//HelloObj = new Hello();
}

private Hello m_HelloObj;
public Hello HelloObj
{
get
{
if (m_HelloObj == null)
{
m_HelloObj = new Hello();
}
return m_HelloObj;
}
set
{
m_HelloObj = value;
}
}
}

public class Hello : INotifyPropertyChanged
{
public Hello()
{
Say = "Hello World!";
}
private string m_Say;
public string Say { get { return m_Say; } set { m_Say = value; RaisedPropertyChanged(nameof(Say)); } }

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisedPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}

APP.xml

<Application x:Class="MyWPFSimple5.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyWPFSimple5"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<local:Locator x:Key="vmLocator"/>
</ResourceDictionary>
</Application.Resources>
</Application>



阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6