wpf 如何在代码隐藏中访问在 XAML 中创建的 DataContext 类实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17495937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access DataContext class instance created in XAML in codebehind?
提问by iAteABug_And_iLiked_it
MyDatais a class simply storing a ColorNameproperty.
MyData是一个简单地存储ColorName属性的类。
In XAML I can create an instance for my XAML datacontext by
在 XAML 中,我可以通过以下方式为我的 XAML 数据上下文创建一个实例
<c:MyData x:Key="myDataSource">
Now,
现在,
How do I access and change the ColorName stored in this instance of MyData (which was created in XAML with "myDataSource" key) in my code behind?
如何在后面的代码中访问和更改存储在此 MyData 实例(使用“myDataSource”键在 XAML 中创建)中存储的 ColorName?
I hope the question is clear. I 'd like to change the color programmatically. How do I get hold of the MyData class instance ? Thank you
我希望这个问题很清楚。我想以编程方式更改颜色。如何获取 MyData 类实例?谢谢
<DockPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample">
<DockPanel.Resources>
<c:MyData x:Key="myDataSource"/>
</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource myDataSource}"/>
</DockPanel.DataContext>
<Button Background="{Binding Path=ColorName}"
Width="150" Height="30">I am bound to be RED!</Button>
</DockPanel>
回答by PoweredByOrange
To access a resource from code-behind, give the DockPanela name and then:
要从代码隐藏访问资源,请提供DockPanel名称,然后:
var resource = dockPanel.Resources["myDataSource"];
Alternatively, you can get its DataContext:
或者,您可以获取其 DataContext:
var dataContext = dockPanel.DataContext as MyData

