将对象从MainWindow传递给CustomClass

时间:2014-03-22 18:07:31

标签: c# wpf xaml

如何将对象从MainWindow.xaml.cs传递到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>

2 个答案:

答案 0 :(得分:1)

您只需在代码后面的MyClass分配属性:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var b = new Building();
        b.Name = "My Building";

        myClass.MyBuilding = b;
    }
}

class MyClass
{
    public Building MyBuilding {get; set;}
}

答案 1 :(得分:1)

如果只有一个您感兴趣的对象,可以在MyClass中声明Dependency Property并可以通过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类型的属性:

public Building MyBuilding { get; set;}
public MainWindow()
{
    InitializeComponent();
    DataContext = this;
    MyBuilding = new Building();
    b.Name = "My Building";
}

如果MyBuilding可以更改应用程序执行,请确保在MainWindow类上实现INotifyPropertyChanged,并且每当MyBuilding设置时都会引发属性更改事件。

<强> XAML

<customclasses:MyClass x:Name="myClass" MyBuilding="{Binding MyBuilding}"/>