无法从外部类访问wpf控件

时间:2014-02-13 14:45:57

标签: wpf class xaml

我想从外部类调用主窗口上的标签控件。但是班级不承认它。

我的文件结构是这样的

ZoomBorder.cs
MainWindow.xaml

XAML:

<Window x:Class="GUI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:PanAndZoom"
        Title="PanAndZoom" Height="600" Width="900" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="100"></RowDefinition>
        </Grid.RowDefinitions>
        <local:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
            <!--<Image Source="/GUI;component/Images/Desert.jpg"/>-->
            <Canvas Width="300" Height="300" Background="Green"></Canvas>
        </local:ZoomBorder>
        <StackPanel Grid.Row="1">
            <Label x:Name="pos" x:FieldModifier="public">Position</Label>
        </StackPanel>
    </Grid>
</Window>

ZoomBorder.cs:

public class ZoomBorder : Border
{
   ...
   private void SomeMethod()
   {
       // this doesn't work!
       pos.Content = "This label is changed by ZoomBorder!";
   }
}

3 个答案:

答案 0 :(得分:1)

您尝试的方式仅适用于在同一类中定义的属性:

pos.Content = "This label is changed by ZoomBorder!";

如果来自其他类的静态属性,您可以通过以下方式访问它:

MainWindow.pos = ....
//or generally
ClassName.PropertyName = ....

不幸的是,XAML中的UI控件不是静态属性。如果来自其他类的非静态属性,则需要类实例来访问该属性:

MainWindow mainWindowInstance = new MainWindow();
mainWindowInstance.pos = ....

上面的代码段只是示例,在您的情况下,您需要找到一种方法将显示的当前MainWindow实例传递给ZoomBorder,而不是像本示例所示创建新实例。

答案 1 :(得分:0)

没有理由这样做。你要做的几乎相当于:

class Parent // = MainWindow
{
   object xxx;
   Child child;
}

class Child // = ZoomBorder
{
   void SomeFunction()
   {
       this.xxx = ...; // Doesn't work, the class Child doesn't have any xxx field
   }
}

答案 2 :(得分:0)

这应该有用。

var wnd = Application.Current.MainWindow as MainWindow;
var label = wnd.pos;