【问题标题】:Can you programmatically set a property in a ControlTemplate from a ChildWindow?您可以从 ChildWindow 以编程方式在 ControlTemplate 中设置属性吗?
【发布时间】:2012-10-06 03:05:44
【问题描述】:

我正在开发一个 Silverlight 应用程序,该应用程序具有为应用程序中不同类型的子窗口定义样式的资源文件。 <Style> 包含带有各种内容的 <ControlTemplate> 标记。有没有办法从子窗口的类中设置<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 的值。

这可能吗?

谢谢

【问题讨论】:

  • 您是否尝试过将图像源设为 BitmapImage 资源? (用一个键可以说 myImage)。然后使用 {DynamicResource myImage} 从图像源引用该资源,并从您的子控件设置该资源
  • @zahir:不,我没试过。你有我可以阅读的关于该技术的文章/博客吗?

标签: silverlight binding


【解决方案1】:

在您的资源中,您可以这样做:

<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。当您拥有视图模型而不是代码隐藏时,这些事情会变得更简单。您可能想查看为 MVVM 设计的相关 msdn pagecodeproject samplea toolkita validation mechanism

【讨论】:

  • 我应该把 放在哪里?我把它放在资源文件的顶部(我必须使用属性UriSource,而不是Source,顺便说一句),但是当我使用Resources["MyImage"] 时,我会返回null。另外,我使用的是 Silverlight 5,而不是 WPF。
【解决方案2】:

@zahir 的回答为我指明了正确的方向,但要让它在 Silverlight 中工作,我必须执行以下操作:

首先,我将&lt;BitmapImage&gt; 标记添加到我的资源文件中,使用UriSource 属性指定默认值。

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

接下来,我在&lt;ControlTemplate&gt; 中这样引用它:

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

然后,在我的代码隐藏类中,我可以像这样修改UriSource 属性:

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

当然,UriSource 的精确值取决于您处理图像资产的方式、它们的位置等。

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 2011-02-24
    • 2021-05-20
    • 2012-08-20
    相关资源
    最近更新 更多