c# - 在代码隐藏中修改列表框的数据模板属性

标签 c# wpf xaml datatemplate code-behind

根据下面显示的代码,我在 XAML 中有一个列表框。

<ListBox name="myListBox">  
  <ListBox.ItemTemplate>
    <DataTemplate>
       <Image Source="{Binding Path=Image}" Width="175" Height="175" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

在基于条件的运行时,我想使用隐藏代码将 heightwidth 属性更改为另一个值。请有人指导我实现所需的功能。

非常感谢

最佳答案

我认为实现此目的最简单的方法可能是将图像的宽度和高度绑定(bind)到两个属性。如果您想更改所有图像的宽度和高度,您可以在代码后面使用两个属性,如果您希望能够单独执行它,那么只需执行相同的操作但绑定(bind)集合项中的属性。

<ListBox name="myListBox"> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <Image Source="{Binding Path=Image}"
                   Width="{Binding ElementName=myWindow,
                                   Path=ListBoxTemplateWidth}"
                   Height="{Binding ElementName=myWindow,
                                    Path=ListBoxTemplateHeight}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

在后面的代码中你定义了两个属性

private double m_listBoxTemplateHeight;
public double ListBoxTemplateHeight
{
    get
    {
        return m_listBoxTemplateHeight;
    }
    private set
    {
        m_listBoxTemplateHeight = value;
        OnPropertyChanged("ListBoxTemplateHeight");
    }
}
private double m_listBoxTemplateWidth;
public double ListBoxTemplateWidth
{
    get
    {
        return m_listBoxTemplateWidth;
    }
    private set
    {
        m_listBoxTemplateWidth = value;
        OnPropertyChanged("ListBoxTemplateWidth");
    }
}

if (someCondition == true)
{
    ListBoxTemplateHeight = 200;
    ListBoxTemplateWidth = 200;
}

这样,ListBoxItems 的大小将随着图像的宽度/高度而增加/减小。

关于c# - 在代码隐藏中修改列表框的数据模板属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4184959/

相关文章:

wpf - Windows Phone 8.1 应用程序中的按钮大小不是预期的

c# - 将 DataGridColumnHeader 与所选行的属性绑定(bind)

c# - 为什么 "abcd".StartsWith ("") 返回真?

c# - 通过在文本字段上按 Enter 键来在用户控件上提交表单不起作用

c# - 在页面上查找特定类型的所有 UserControl,可能使用 LINQ?

c# - WPF Databinding DataTrigger 根据 bool 值改变形状的颜色

c# - 我的项目使用哪个 appSetting.config 文件

c# - 使用 Prism、MVVM、MEF 在 WPF 中动态生成控件

c# - MVVM 模式 - 可以将 UI 相关数据放入模型中吗?

c# - 禁用 WPF ComboBox 的下拉菜单