Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在controltemplate中更改图像源?_C#_Wpf_Image - Fatal编程技术网

C# 如何在controltemplate中更改图像源?

C# 如何在controltemplate中更改图像源?,c#,wpf,image,C#,Wpf,Image,我的MyResourceDictionary.xaml文件中有这样的模板 <ControlTemplate TargetType="{x:Type Button}" x:Key="ImageButtonTemplatepurpleSmall" > <Grid> <Image Source="images\button_purple_up_76.jpg" Name="image" /> </Gr

我的MyResourceDictionary.xaml文件中有这样的模板

<ControlTemplate TargetType="{x:Type Button}" x:Key="ImageButtonTemplatepurpleSmall"  >
        <Grid>
            <Image Source="images\button_purple_up_76.jpg" Name="image"  />

        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter TargetName="image" Property="Source" Value="images\button_purple_hover_76.jpg" />
            </Trigger>
            <Trigger Property="IsPressed" Value="true">
                <Setter TargetName="image" Property="Source" Value="images\button_purple_depressed_76.jpg" />
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
但是它总是返回空值,我怎么能改变这个的图像源呢? 已更新

public override void OnApplyTemplate()
        {
            //base.OnApplyTemplate();
            //Image RecTangleObj = (Image)btnBack.Template.FindName("image", btnBack);
            //if (RecTangleObj != null)
            //{ 

            //}
        }

当屏幕上没有呈现子内容时,将调用窗口的OnApplyTemplate


将此代码放在加载的事件中,它将正常工作。

您将此代码放在哪里?模板是否已应用于按钮?我怀疑你是在控件的构造函数中完成的。是的,模板已经应用。如果用户上传了新图像@rohitvats,我想更改该图像。请检查答案并让我知道,以防它对你不起作用。很好,谢谢。我还有一个问题,我想更改图像而不引用btnBack,所以所有按钮连接到这个应用了新的图像首先你不应该从代码后面做它。在ViewModel中具有适当的属性,并使用该属性绑定(这是正确的方式),并在任何更改集上绑定该属性,以便自动更新。如果您仍然想这样做,您必须使用按钮的引用:(好的,但我有上传按钮,所以对此有什么建议吗?使用viewmodel?您需要将源代码绑定到viewmodel中的某些属性。您是否在MVVM中工作过?这是如何执行此操作的示例
。但如果您没有使用它,那么您需要先了解它。网络上有很多可用的文章。这是一大堆新内容问题。所以,我建议后续问题在这里发布另一个问题,以便更多的观众可以看到。
public override void OnApplyTemplate()
        {
            //base.OnApplyTemplate();
            //Image RecTangleObj = (Image)btnBack.Template.FindName("image", btnBack);
            //if (RecTangleObj != null)
            //{ 

            //}
        }