日期:2014-05-17  浏览次数:20673 次

WPF,请问这里为什么不能使用Name

<Window.Resources>
    <Button x:Key="dd" Name="button1" Background="Red"/>
</Window.Resources>
<Grid>
    <Button Name="button2" Content="Button" HorizontalAlignment="Left" Margin="131,120,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>



private void button_Click(object sender, RoutedEventArgs e)
{
    button2.Background = button1.Background;
}


我知道可以用FindResource方法获取资源。不过,这段代码中,资源中的Button设置了Name属性为button1,在后台使用的时候,为什么不能使用button1呢?

------解决方案--------------------
这种问题问的
<Window.Resources>
    <Button x:Key="dd" Name="button1" Background="Red"/>
</Window.Resources>
你也知道这个是写在资源里面的喽
而button2.Background = button1.Background;
这句的本质是给一个类里面的property(button2.Background)赋值
但是 button1.Background这个button1没有在当前的window中 而是在资源中
换句话说button1没有在当前的类中声明。。。。。。
所以就不能直接这样写喽
------解决方案--------------------
button btn=sender  as button  btn的Name就是button1



------解决方案--------------------
引用:
Quote: 引用:

换句话说button1没有在当前的类中声明。。。。。。
所以就不能直接这样写喽

哦,是这样,不过我想问下,button1没有在当前的类中声明,它明明是在<Window>标签下声明的啊

http://msdn.microsoft.com/zh-cn/library/vstudio/ms752326(v=vs.110).aspx
你添加的是资源而已。。。。。看看msdn的解释吧