MyData是一个只存储ColorName属性的类。
在xaml中,我可以通过

<c:MyData x:Key="myDataSource">

现在,
如何访问和更改mydata实例(在xaml中用“mydatasource”键创建)中存储的colorname?
我希望问题是清楚的。我想用程序改变颜色。如何获取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>

最佳答案

要从代码隐藏访问资源,请为DockPanel命名,然后:

var resource = dockPanel.Resources["myDataSource"];

或者,您可以获取其数据上下文:
var dataContext = dockPanel.DataContext as MyData

07-24 09:38
查看更多