代码之家  ›  专栏  ›  技术社区  ›  Scott Mitchell

您能从ChildWindow以编程方式在ControlTemplate中设置属性吗?

  •  0
  • Scott Mitchell  · 技术社区  · 13 年前

    我正在开发一个Silverlight应用程序,该应用程序具有为应用程序中不同类型的子窗口定义样式的资源文件。这个 <Style> 包含 <ControlTemplate> 具有各种内容的标记。是否有方法设置在 <控制模板> 来自儿童窗口的班级?

    例如,假设在资源文件中,我有如下标记:

    <Style x:Key="MyChildWindowStyle" TargetType="sdk:ChildWindow">
      <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="sdk:ChildWindow">
               <Grid x:Name="Root">
                  ...
                  <Image Source="/Assets/image.png" />
                  ...
               </Grid>
            </ContentTemplate>
       </Setter>
    </Style>
    

    现在假设我有许多子窗口被配置为使用这种样式。我希望能够从这些子窗口中的代码中以编程方式更改图像的值 Source

    这可能吗?

    谢谢

    2 回复  |  直到 13 年前
        1
  •  0
  •   zahir    13 年前

    在您的资源中,您可以做到以下几点:

    <BitmapImage x:Key="MyImage" Source="/Assets/image.png"/>
    
    <Style x:Key="MyChildWindowStyle" TargetType="sdk:ChildWindow">
        ...
        <Image Source="{DynamicResource MyImage}" />
        ...
    </Style>
    

    然后,在孩子窗口后面的代码中,您可以执行以下操作:

    Resources["MyImage"] = new BitmapImage(new Uri("/Assets/other-image.png"));
    

    但是,如果您的子窗口类在另一个程序集中,则编写的uri应该有所不同:

    Resources["MyImage"] = new BitmapImage(new Uri("pack://application:,,,/MyOtherAssemblyShortName;component/Assets/other-image.png"));
    

    你可以检查 msdn page 用于包uri格式。

    但我建议您使用MVVM模式,以便在绑定、样式等方面充分利用WPF。当您有了视图模型而不是代码时,这些事情就会变得更简单。你可以查看相关信息 msdn page codeproject sample , a toolkit a validation mechanism 专为MVVM设计。

        2
  •  0
  •   Scott Mitchell    13 年前

    @zahir的回答为我指明了正确的方向,但为了让它在Silverlight中发挥作用,我必须做以下事情:

    首先,我添加了 <BitmapImage> 标记到我的资源文件,使用 UriSource 属性来指定默认值。

    <BitmapImage x:Key="MyImage" UriSource="../Assets/DefaultImage.png" />
    

    接下来,我在 <ControlTemplate> 就像这样:

    <Image ... Source="{StaticResource MyImage}"/>
    

    然后,在我的代码隐藏类中,我能够修改 尿液来源 这样的属性:

    BitmapImage img = (Application.Current.Resources["MyImage"] as BitmapImage);
    if (img != null)
        img.UriSource = "../Assets/NewImage.png";
    

    当然 尿液来源 将取决于您处理图像资产的方式、它们的位置等。