我们说我有一个像这样的简单ListBox:
<!--Data template for the color samples-->
<DataTemplate x:Key="MyDataTemplate">
<ContentControl>
<Border BorderThickness="4"
Margin="4,4,4,0"
Height="{Binding BorderSize}"
Width="{Binding BorderSize}">
<Grid>
<Polygon Points"{Binding BorderSize, Converter={StaticResource SomeConverterThatDoesStuff}}"/>
<Canvas Background="{StaticResource PhoneAccentBrush}"/>
<Image Source={Binding Image}/>
</Grid>
</Border>
</ContentControl>
</DataTemplate>
<ListView ItemTemplate="{StaticResource MyDataTemplate}"
ItemsSource="{Binding Source}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
现在,假设我的Source中有一定数量的元素(当然它可能会有所不同),我希望每行显示固定数量的元素。
正如您所看到的,我实际上使用了这种解决方法:在我的DataModel中我有这样的东西:
public class DataTemplateViewModel : INotifyPropertyChanged
{
public static double BorderSize
{
get { return (Window.Current.Bounds.Width - 80) / 4; }
}
private ImageSource _Image;
public ImageSource Image
{
get { return this._Image; }
set
{
if (this._Image != value)
{
this._Image = value;
OnNotifyPropertyChanged();
}
}
}
// Let's say here I have the interface implementation...
}
如您所见,我的BorderSize参数返回屏幕宽度减去固定常量(ListView外部各种UI元素的边距)除以4。 现在,通过这个技巧,我可以在每一行显示4×4的图像,这就是我想要的。
我的观点是,就我所知,我的DataModel根本不应该连接到我的视图级别,而是在此我计算其DataTemplate的有效像素宽度。
它工作正常,但我想有更好的方法。
如何在运行时设置DataTemplate的某些属性(在这种情况下是该边框的高度和宽度)?
谢谢! 塞尔吉奥
答案 0 :(得分:0)
您可以在ViewModel中为BorderSize定义属性
private double borderSize=(Window.Current.Bounds.Width - 80) / 4;
public double BorderSize
{
get { return borderSize; }
set { borderSize = value; }
}
并简单地将此属性绑定到DataTemplate
中网格或边框的高度和宽度<Border Height={Binding BorderSize} Width={Binding BorderSize}/>