问题描述
如何将对象从 MainWindow.xaml.cs
传递到 MyClass.cs
?
How can I pass an object from MainWindow.xaml.cs
to MyClass.cs
?
- MainWindow.xaml
MainWindow.xaml.cs
- MyClass.cs
- Building.cs
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var b = new Building();
b.Name = "My Building";
}
}
XAML:
<Window x:Class="CustomClasses.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customclasses="clr-namespace:CustomClasses"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="150"></RowDefinition>
</Grid.RowDefinitions>
<customclasses:MyClass x:Name="myClass">
</customclasses:MyClass>
<StackPanel Grid.Row="1">
</StackPanel>
</Grid>
</Window>
推荐答案
如果只有一个您感兴趣的对象,您可以在 MyClass 中声明 Dependency Property
并且可以通过 XAML 进行绑定.
If there's only one object you are interested in you can declare Dependency Property
in MyClass and can bind through XAML.
public class MyClass : Border
{
public Building MyBuilding
{
get { return (Building)GetValue(MyBuildingProperty); }
set { SetValue(MyBuildingProperty, value); }
}
public static readonly DependencyProperty MyBuildingProperty =
DependencyProperty.Register("MyBuilding", typeof(Building),
typeof(MyClass));
}
在MainWindow
中,你必须声明Building类型的属性:
and in MainWindow
, you have to declare property of type Building:
public Building MyBuilding { get; set;}
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyBuilding = new Building();
b.Name = "My Building";
}
如果 MyBuilding
可以更改应用程序的执行,请确保在 MainWindow 类上实现 INotifyPropertyChanged
,并且每当设置 MyBuilding 时都会引发属性更改事件.
In case MyBuilding
can change over the application execution make sure you implement INotifyPropertyChanged
on MainWindow class and property changed event is raised whenever MyBuilding gets set.
XAML
<customclasses:MyClass x:Name="myClass" MyBuilding="{Binding MyBuilding}"/>
这篇关于将对象从 MainWindow 传递给 CustomClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!