首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

WPF如何实现数据和控件的绑定

2013-08-16 
WPF怎么实现数据和控件的绑定例如textbox,怎么让他随着我定义的string型变量的改变而显示不同的字符?一样

WPF怎么实现数据和控件的绑定
例如textbox,怎么让他随着我定义的string型变量的改变而显示不同的字符?

一样的啊。假设项目文件结构如下:WPF如何实现数据和控件的绑定

<Window x:Class="WpfTest.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" Height="300" Width="300">
    <Grid>
        <Image Height="150" HorizontalAlignment="Left" Margin="12,12,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" Source="{Binding Path=MyString}" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="40,176,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>


using System;
using System.ComponentModel;
using System.Windows;

namespace WpfTest
{
    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));


            }
        }

        private String m_mystring = "/Images/Bluehills.jpg";
        public String MyString
        {
            get { return m_mystring; }
            set { 
                m_mystring = value; 
                NotifyPropertyChanged("MyString");
            }
        }

        public Window2()
        {
            InitializeComponent();

            this.DataContext = this;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MyString = "/Images/Sunset.jpg";
        }
    }
}

热点排行