WPF通过xaml初始化一个类的对象后,从代码怎么访问这个对象?
// MyClass.cs
namespace SimpleBinding
{
class MyClass
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
}
// Window1.xaml
<Window x:Class="SimpleBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sb="clr-namespace:SimpleBinding"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.Resources>
<sb:MyClass x:Key="MyKey" Name="AdoDotNet" Age="20" />
</Grid.Resources>
<Grid.DataContext>
<Binding Source="{StaticResource MyKey}" />
</Grid.DataContext>
...
这种情况下怎样从代码访问通过xmal初始化的这个对象?
------解决方案--------------------<Grid Name="myGrid" ...>
//.cs
MyClass cls = myGrid.Resources["MyKey"] as MyClass;
// cls.Name, cls.Age