C# 将绑定源更改为另一个CLR对象
这主要是出于好奇,希望能帮助我更好地理解绑定、XAML和扩展语法 因此,我只想将绑定源从MainWindow更改为我在MainWindow中实例化的对象 这是我的C#代码: 还有我的XAMLC# 将绑定源更改为另一个CLR对象,c#,wpf,xaml,C#,Wpf,Xaml,这主要是出于好奇,希望能帮助我更好地理解绑定、XAML和扩展语法 因此,我只想将绑定源从MainWindow更改为我在MainWindow中实例化的对象 这是我的C#代码: 还有我的XAML <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.
<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方法中声明,否则您将无法获得此。myfavclass实例
Source=myfavclass
这是错误的<代码>源代码只能使用如下元素语法直接分配:
<Binding>
<Binding.Source>
<!-- value here -->
</Binding.Source>
</Binding>
Text="{Binding Source={StaticResource someKey}, Path=MyInt}"
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;
}
}
}
或者使用新功能{x:Reference}
直接获取对XAML中某个命名元素的引用:
Text="{Binding Source={x:Reference someName}, Path=MyInt}"
此外,myfavclass
在代码隐藏中声明为局部变量。它无法在XAML代码中使用(引用)
您正在执行称为多视图模型的操作。如果是这样,您应该为控件提供多个DataContext。我更喜欢使用嵌套视图模型。要实现这一点,您可以尝试修改main窗口
,如下所示:
<Binding>
<Binding.Source>
<!-- value here -->
</Binding.Source>
</Binding>
Text="{Binding Source={StaticResource someKey}, Path=MyInt}"
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代码中,您可以将文本绑定到MyFavClass.MyInt
,注意DataContext
隐式地是绑定的源,因此您只需要指定路径即可:
<TextBlock Height="50" Width="48" Margin="200,100,100,100"
Text="{Binding Path=MyFavClass.MyInt}"/>
您的MyInt
没有使用INotifyPropertyChanged
正确实现(但我希望您已经知道)。您认为myFavClass在没有任何可访问属性的情况下应该如何可用?您可以创建MyFavClass属性并将演示文稿绑定到该属性。嗨,Ivan。对不起,我不太明白。你是说访问myfavclass的唯一方法是创建一个属性吗?我这样问只是因为我做了相反的事情。我已经设置好了。DataContext=myfavclass;然后,如果要更改绑定的源,则需要在主窗口中设置一个属性(如MyInt1),该属性将引用favclass的MyInt属性,而将文本框设置为MyInt1将直接引用MyInt。