摘要:[C#]DataBinding With DataContext 後置變更Binding 資料
xaml
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="300">
<StackPanel Margin="15">
<WrapPanel>
<TextBlock>Before Label Name:</TextBlock>
<Label Content="{Binding Path=Name, ElementName=theLabel}"/>
<TextBlock>After Label Name:</TextBlock>
<Label Name="theLabel" Content="{Binding Name}" />
</WrapPanel>
<WrapPanel>
<Button Click="Button_Click">Button</Button>
</WrapPanel>
</StackPanel>
</Window>
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.ComponentModel;
namespace WpfApplication2
{
///
/// MainWindow.xaml 的互動邏輯
///
public partial class MainWindow : Window
{
class TestObject : INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (_name == value) return;
_name = value;
OnPropertyChanged("Name");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
TestObject t = new TestObject();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
theLabel.DataContext = t;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
t.Name = "Foo";
}
}
}