[英]Change The Binding Source To Another CLR Object
這基本上是出於好奇的問題,希望能幫助我更好地理解綁定,XAML和擴展語法。
所以我只想將綁定源從MainWindow更改為在MainWindow中實例化的對象。
這是我的C#代碼:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
favclass myfavclass = new favclass();
InitializeComponent();
this.DataContext = this;
}
string _myString = "hello";
public string MyString
{
get { return _myString; }
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
public class favclass : INotifyPropertyChanged
{
int _myint = 34;
public int MyInt
{
get { return _myint; }
set { _myint = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
}
和我的XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" >
<Grid>
<TextBlock Height="50" Width="50" Text="{Binding MyString}"/>
<TextBlock Height="50" Width="48" Margin="200,100,100,100"
Text="{Binding Source=myfavclass, Path=MyInt}"/>
</Grid>
</Window>
如您所見,我要首先從主窗口顯示MyString屬性。
然后,我想顯示myfavclass對象中的MyInt。 但是,當然不會出現MyInt。 我嘗試了所有我能想到的變化。
我缺少什么XAML? 為什么我沒有使用XAML?
謝謝
favclass myfavclass =新的favclass(); 應該從init方法中聲明,否則您將無法獲得this.myfavclass實例
Source=myfavclass
這是錯誤的。 只能使用以下元素語法直接分配Source
:
<Binding>
<Binding.Source>
<!-- value here -->
</Binding.Source>
</Binding>
或者,您可以使用StaticResource
或DynamicResoure
或某些自定義MarkupExtension
如下所示:
Text="{Binding Source={StaticResource someKey}, Path=MyInt}"
或使用新功能{x:Reference}
直接引用XAML中的某些命名元素:
Text="{Binding Source={x:Reference someName}, Path=MyInt}"
此外, myfavclass
在后面的代碼中被聲明為局部變量。 無法在XAML代碼中使用(引用)它。
您正在執行稱為多個視圖模型的操作。 如果是這樣,則應為控件提供多個DataContext。 我更喜歡使用嵌套的視圖模型。 要實現此目的,您可以嘗試如下修改MainWindow
:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
_myfavclass = new favclass();
InitializeComponent();
this.DataContext = this;
}
private readonly favclass _myfavclass;
//we will use this property inside XAML code
public favclass MyFavClass {
get {
return _myfavclass;
}
}
}
現在,在XAML代碼中,您可以將Text綁定到MyFavClass.MyInt
,請注意DataContext
是Binding的隱式源,因此您只需要指定Path
:
<TextBlock Height="50" Width="48" Margin="200,100,100,100"
Text="{Binding Path=MyFavClass.MyInt}"/>
您的MyInt
無法使用INotifyPropertyChanged
正確實現(但我希望您已經知道這一點)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.