如何在C#WPF中动态更改列表框项目大小? [英] How to change listbox item size dynamically in C# WPF?

查看:76
本文介绍了如何在C#WPF中动态更改列表框项目大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我在wpf mainindow中创建了列表框,它将显示完美的图像平铺样式。

现在我有还有一个窗口,包含3个选项,如小(160Height,100 Width),中(220H,140W),大(280H,180H)作为单选按钮,并应用按钮,

一旦我选择媒体然后单击应用按钮,然后我的列表框项目大小应为220H,140W。喜欢小adn大怎么办?

以下是我的列表框。



 <   ListBox     l:ListBoxSelector.Enabled   =  {Binding ElementName = UC,Path = MouseSelection,UpdateSourceTrigger = PropertyChanged }  

FocusVisualStyle = < span class =code-keyword> {x:Null} IsEnabled = {Binding ElementName = LoadingAdorner,Path = IsAdornerVisible,
Converter = {StaticResource BoolReverse},UpdateSourceTrigger = PropertyChanged}


ItemsSource = {Binding ElementName = UC,Path = ThumbImages,IsAsync = True,UpdateSourceTrigger = PropertyChanged}

x:FieldModifier = public 名称 = listBoxComposerThumbs BorderBrush = < span class =code-keyword>透明

背景 = {DynamicResource ThumbnailBackgroundColor} 保证金 = 5,48,5,10 Drop = listBoxComposerThumbs_Drop

< span class =code-attribute> AllowDrop = True SelectionMode = 扩展 < span class =code-attribute> SelectionChanged = OnThumbViewSelectChanged

ScrollViewer.Horizo​​ntalScrollBarVisibility = 已禁用 ScrollViewer.VerticalScrollBarVisibility = 自动

ScrollViewer.CanContentScroll = True MouseDoubleClick = ThumbView_MouseDoubleClick

MouseRightButtonDown < span class =code-keyword> = ThumbView_MouseLeftBtnDown MouseLeftButtonDown = ThumbView_MouseLeftBtnDown

RenderOptions.BitmapScalingMode = < span class =code-keyword> HighQuality RenderOptions.EdgeMode = 别名

< span class =code-attribute> LayoutUpdated = listBoxComposerThumbs_LayoutUpdated KeyDown = listBoxComposerThumbs_KeyDown >
< ListBox.Style >
< 样式 TargetType = ListBox &g t;
< Setter 属性 = FocusVisualStyle = {x:Null} / >
< EventSetter 事件 = ContextMenuOpening 处理程序 = listBoxComposerWorkSpace_ContextMenu / >
< / Style >
< /ListBox.Style>
< ListBox.ContextMenu >
< ContextMenu 样式 = {x:Null} >
< MenuItem 样式 = {x:Null} 标题 = {x:静态文化:Resources.CutMenu} < span class =code-attribute> 前景 = 黑色 TextBlock.Foreground = 黑色 InputGestureText = Ctrl + X IsEnabled = False FontFamily = Segoe UI Regular FontSize = 12 / >
< MenuItem 样式 = < span class =code-keyword> {x:Null} 标题 = {x:静态文化:Resources.CopyMenu} 前景 = 黑色 TextBlock.Foreground = 黑色 InputGestureText = Ctrl + C IsEnabled = False FontFamily = Segoe UI Regular FontSize = 12 / >
< MenuItem S tyle = {x:Null} 标题 = {x:静态culture:Resources.PasteMenu} 前景 = 黑色 TextBlock.Foreground = 黑色 < span class =code-attribute>标记 = P 点击 = PasteBtn_Click InputGestureText = Ctrl + V FontFamily = Segoe UI Regular FontSize = 12 / >
< 分隔符/ >
< MenuItem 样式 = {x:Null} 标题 = {x:静态文化:Resources.DeleteText} 前景 = 黑色 TextBlock.Foreground = 黑色 InputGestureText = Del IsEnabled = False FontFamily = Segoe UI Regular 字体大小 = 12 / >
< MenuItem 样式 = {x:Null} 标题 = {x:静态文化:Resources.SelectAllMenu} 前景 = 黑色 < span class =code-attribute> TextBlock.Foreground = 黑色 标记 = S 点击 = SelectAllBtn_Click InputGestureText = Ctrl + A FontFamily = Segoe UI Regular FontSize = 12 / >
< 分隔符/ >
< MenuItem 样式 = {x:Null} 标题 = {x:静态文化:Resources.InsertMenu} 前景 = 黑色 TextBlock.Foreground = 黑色 标记 = 点击 = InsertBlankPageBtn_Click InputGestureText = Ctrl + B FontFamily = Segoe UI Regular FontSize = 12 / >
< / ContextMenu >
< / ListBox.ContextMenu >
< ItemsControl.ItemsPanel >
< ItemsPanelTemplate >
< UniformGrid SizeChanged = scroll_SizeChanged = {Binding ElementName = UC,Path = TileColumns}

< span class =code-attribute> FocusVisualStyle = {x:Null} VerticalAlignment = 热门 / >
< / ItemsPanelTemplate >
< / ItemsControl.ItemsPanel >
< ItemsControl.ItemTemplate >
< DataTemplate >
< Grid >
< Grid.RowD定义 >
< RowDefinition 高度 = * / >
< RowDefinition 高度 = 自动 / >
< / Grid.RowDefinitions >

< Bor der >
< Border.Effect >
< DropShadowEffect BlurRadius = 20 ShadowDepth < span class =code-keyword> = 0 不透明度 = 0.8 颜色 < span class =code-keyword> = 黑色 / >
< / Border.Effect >
< 网格 背景 = 白色 Horizo​​ntalAlignment = >
< 网格 x:名称 = < span class =code-keyword> ListItemPanel >
< < span class =code-leadattribute> Grid.Style >
< 样式 TargetType = 网格 >
< EventSetter 事件 = ContextMenuOpening 处理程序 = listBoxCom poserThumbs_ContextMenu / >
< / Style >
< / Grid.Style >
< Grid.ContextMenu >
< ContextMenu 样式 = {x:Null} >
< MenuItem 样式 = {x:Null} 标题 = { x:静态文化:Resources.CutMenu} 命令 = 剪切 CommandTarget = {Binding Path = PlacementTarget,RelativeSource = {RelativeSource AncestorType = {x:Type ContextMenu}}} InputGestureText = Ctrl + X FontFamily = Segoe UI Regular FontSize =\"12\"/>
<MenuItem Style=\"{x:Null}\" Header=\"{x:Static culture:Resources.CopyMenu}\" Command=\"Copy\" CommandTarget=\"{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" InputGestureText=\"Ctrl+C\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
<MenuItem < span class=\"code-attribute\">Style=\"{x:Null}\" Header=\"{x:Static culture:Resources.PasteMenu}\" Tag=\"P\" Command=\"Paste\" CommandTarget=\"{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" InputGestureText=\"Ctrl+V\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
<Separator/>
<MenuItem Style=\"{x:Null}\" Header=\"{x:Static culture:Resources.DeleteText}\" Command=\"Delete\" CommandTarget=\"{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" InputGestureText=\"Del\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
<MenuItem Style=\"{x:Null}\" Header=\"{x:Static culture:Resources.SelectAllMenu}\" Command=\"SelectAll\" CommandTarget=\"{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" Input GestureText=\"Ctrl+A\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
<Separator/>
<MenuItem Style=\"{x:Null}\" Header=\"{x:Static culture:Resources.InsertMenu}\" Command=\"Pause\" CommandTarget=\"{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" InputGestureText=\"Ctrl+B\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
<Separator/>
<MenuItem Style=\"{StaticResource MenuSelectPaper}\" Header=\"{x:Static culture:Resources.SelectPSMenu}\" Tag=\"{Binding BinNo,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}\" x:Name=\"SelectPaperMenu\" FontFamily=\"Segoe UI Regular\" FontSize=\"12\"/>
</ContextMenu>
</Grid.ContextMenu>

<Grid.RowDe finitions>
<RowDefinition Height=\"Auto\"/>
<RowDefinition Height=\"Auto\"/>
<RowDefinition Height=\"Auto\"/>
</Grid.RowDefinitions>

<Rectangle x:Name=\"HeaderRect\" Grid.Row=\"0\" Fill=\"Red\" Height=\"6\"

Visibility=\"{Binding Path=BHdr,Converter={StaticResource BoolVisble},UpdateSourceTrigger=PropertyChanged}\"/>
<!--<Image Grid.Row=\"1\" Source=\"{Binding ThumbnailImage}\" Stretch=\"Fill\" Height=\"{Binding Path=ImageHeight,Converter={StaticResource HeightConvert},ConverterParameter=260,UpdateSourceTrigger=PropertyChanged}\" Width=\"{Binding Path=ImageWidth,Converter={StaticResource WidthConvert},ConverterParameter=260,UpdateSourceTrigger=PropertyChanged}\">-->
<Image Grid.Row=\"1\" Source=\"{Binding ThumbnailImage}\" Stretch=\" Fill\" Height=\"{Binding Path=RectHeight,UpdateSourceTrigger=PropertyChanged}\"

Width=\"{Binding Path=RectWidth,UpdateSourceTrigger=PropertyChanged}\">
< Image.LayoutTransform>
<RotateTransform Angle=\"{Binding RotateAngle,UpdateSourceTrigger=PropertyChanged}\"/>
</Image.LayoutTransform>
</Image>
<Rectangle
x:Name=\"FooterRect\" Fill=\"Red\" Grid.Row=\"2\" Height=\"3\" Visibility=\"{Binding Path=BFtr,Converter={StaticResource BoolVisble},UpdateSourceTrigger=PropertyChanged}\"/>
& lt;TextBlock Text=\"{Binding BinNo}\" Visibility=\"Collapsed\"/>
</Grid>

</Grid>
</Border>

<TextBlock Grid.Row=\"1\" Foreground=\"{DynamicResource NofilesForegroundColor}\" HorizontalAlignment=\"Center\">
<Run x:Uid=\"DisplayPage\" Text=\"{x:Static culture:Resources.DisplayPage}\"/>
<Run Text=\"{Binding PageNumber}\"/>
</TextBlock>
</Grid>

</DataTemplate>
</ItemsControl.ItemTemplate>
<ListBox.Resources>
<Style TargetType=\"ListBoxItem\">
<EventSetter Event=\"PreviewMouseLeftButtonDown\" Handler=\"ListBoxItem_PreviewMouseLeftButtonDown\"< span class=\"code-keyword\">/>
<EventSetter Event=\"PreviewMouseLeftButtonUp\" Handler=\"ListBoxItem_PreviewMouseLeftButtonUp\"/>
<EventSetter Event=\"Drop\" Handler=\"ListBoxItem_Drop\"/>
<Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\"/>
<Setter Property=\"AllowDrop\" Value=\"True\"/>
<Setter Property=\"Background\" Value=\"Transparent\"/>
<Setter Property=\"Padding\" Value=\" 0,0,0,0\"/>
<Setter Property=\"Margin\" Value=\"10,10,10,0\"/>
<Setter Property=\"HorizontalContentAlignment\" Value=\"Center\"/>
<Setter Property=\"VerticalContentAlignment\" Value=\"Center\"/>
<Setter Property=\"HorizontalAlignment\" Value=\"Center\"/>
<Setter Property=\"VerticalAlignment\" Value=\"Bottom\"/>
<Setter Property=\"Template\">
<Setter.Value>
<ControlTemplate TargetType=\"ListBoxItem\">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=\"Aut o\"/>
<ColumnDefinition Width=\"*\"/>
<ColumnDefinition Width=\"Auto\"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column=\"0\" x:Name=\"GLeftBd\" Visibility=\"{Binding ElementName=UC,Path=MouseDragVisibility,UpdateSourceTrigger=PropertyChanged}\" Drop=\"GridDrop\" DragOver=\"GridDragOver\" DragLeave=\"GridDragLeave\" DragEnter=\"GridDragEnter\" Margin=\"-40,0,0,0\" Background=\"#19FFFFFF\">
<Border x:Name=\"LeftBd\" Backgrou nd=\"Black\" Visibility=\"Collapsed\" CornerRadius=\"2\" Width=\"2\" Margin=\"0,5,8,15\" HorizontalAlignment=\"Right\">
<< span class=\"code-leadattribute\">Border.Effect>
<DropShadowEffect BlurRadius=\"8\" ShadowDepth=\"0\" Opacity=\"0.8\" Color=\"Black\"/>
<
/Border.Effect>
</Border>
</Grid>
<Grid Grid.Column=\"1\" x:Name=\"ThumbImageBaseGrid\" HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">
<ContentPresenter x:Name=\"ThumbContentHost\" Margin=\"3\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\"/>
<Rectangle x:Name=\"BackgroundRect\" Fill=\"{x:Null}\" Opacity=\"0\" Margin=\"0\" Stroke=\"{DynamicResource ContentBorderBackgroundColor}\" StrokeThickness=\"3\"/>
</Grid>
<Grid Grid.Column=\"2\" x:Name=\"GRightBd\" Visibility=\"{Binding ElementName=UC,Path=MouseDragVisibility,UpdateSourceTrigger=PropertyChanged}\" Drop=\"GridDrop\" DragOver=\"GridDragOver\" DragLeave=\"GridDragLeave\" DragEnter=\"GridDragEnter\" Margin< span class=\"code-keyword\">=\"0,0,-40,0\" Background=\"#19FFFFFF\">
<Border x:Name=\"RightBd\" Background=\"Black\" Visibility=\"Collapsed\" CornerRadius=\"2\" Width=\"2\" Margin=\"8,5,0,15\" HorizontalAlignment=\"Left\">
<Border.Effect>
<DropShadowEffect BlurRadius=\"8\" ShadowDepth=\"0\" Opacity=\"0.8\" Color=\"Black\"/>
</Border.Effect>
</Border>
</Grid
>
</Grid>
<ControlTemplate.Triggers>
<!--<EventTrigger RoutedEvent=\"Loaded\">
<EventTrigger.Actions>
<BeginStoryboard Storyboard=\"{StaticResource LoadAnimation}\"/>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent=\"Unloaded\">
<EventTrigger.Actions>
<BeginStoryboard Storyboard=\"{StaticResource UnLoadAnimation}\"/>
</EventTrigger.Actions>
</EventTrigger>
-->

<Trigger Property=\"IsSelected\" Value=\"True\">
<Setter TargetName=\"BackgroundRect\" Property=\"Opacity\" Value=\"1\"/>
<!--<Setter TargetName=\"border\" Property=\"BorderThickness\" Value=\"0\"/>
<Setter TargetName=\"border\" Property=\"BorderBrush\" Value=\"Red\"/>
-->

</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property=\"IsSelected\" Value=\"true\"/>
<Condition Property=\"Selector.IsSelectionActive\" Value=\"false\"/>
</MultiTrigger.Conditions>
<Setter TargetName=\"BackgroundRect\" Property=\"Opacity\" Value=\"1\"/>
</MultiTrigger>
<Trigger Property=\"IsEnabled\" Value=\"false\">
<Setter Property=\"Foreground\" Value=\"Transparent\"/>
</Trigger>
<Trigger Property=\"IsMouseOver\" Value=\"True\">
<Setter Property=\"Background\" Value=\"Transparent\"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
< /ListBox>





What I have tried:



I googled but not getting any related solutions. pleas any one can suggest me how to solve this.

解决方案

I’ll take a stab at what you want to do.



You’re trying to dynamically change the size of an image from a selection list in another window. You’re using Data Binding, so I’m going to guess that this is a MVVM project.



Firstly, being a MVVM project, ViewModels (VMs) can’t directly reference UI objects like Windows however VMs can create other VMs. So we need a proxy service to launch a Selector Window using the associate VM:

public interface IViewModel 
{

}

internal interface IWindowService
{
void ShowWindow(IViewModel viewModel);
}

internal class WindowService : IWindowService
{
public void ShowWindow(IViewModel viewModel)
=> (new Window
{
Content = viewModel,
SizeToContent = SizeToContent.WidthAndHeight,
WindowStartupLocation = WindowStartupLocation.CenterScreen
}).Show();
}



For this to work, we need to set the DataTemplate in the App.XAML:

<Application 

x:Class=\"WpfListImageSizer.App\"

xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"

xmlns:vm=\"clr-namespace:WpfListImageSizer\"

xmlns:vw=\"clr-namespace:WpfListImageSizer\"

StartupUri=\"MainWindow.xaml\">
<Application.Resources>
<DataTemplate DataType=\"{x:Type vm:SizeSelectorViewModel}\" >
<vw:SelectorView/>
</DataTemplate>
</Application.Resources>
</Application>



The DataTemplate links the SelectorView to the SizeSelectorViewModel.

Next, as we are using Data Binding, we need to implement the INotifyPropertyChanged event handler for the data model and the VMs. So it is easier to create a base class that implements it:

public abstract class ObservableBase : INotifyPropertyChanged 
{
public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = \"\")
{
if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
{
field = newValue;
PropertyChanged?.Invoke( this new PropertyChangedEventArgs(propertyName));
}
}

public event PropertyChangedEventHandler PropertyChanged ;

public bool IsInDesignMode = > DesignerProperties.GetIsInDesignMode( new DependencyObject());
}



I’ve also added the IsInDesignMode into the base class. This is used to prevent the VS (Visual Studio) Designer from executing specific code in our project - VMs in this case.



Now we need our data models - one for the Image Size selection, and another for our dummy data to test with:

public class ImageSizeModel : ObservableBase 
{
private string title;
public string Title
{
get => title;
set => Set(ref title, value);
}

private double width;
public double Width
{
get => width;
set => Set(ref width, value);
}

private double height;
public double Height
{
get => height;
set => Set(ref height, value);
}
}

public class PersonModel : ObservableBase
{
private string firstname;
public string Firstname
{
get => firstname;
set => Set(ref firstname, value);
}

private string lastname;
public string Lastname
{
get => lastname;
set => Set(ref lastname, value);
}

private string photoUrl;
public string PhotoUrl
{
get => photoUrl;
set => Set(ref photoUrl, value);
}
}





Now for our view models. First, we need the Selector VM:

public class SizeSelectorViewModel : ObservableBase, IViewModel 
{
public SizeSelectorViewModel()
{

}

public SizeSelectorViewModel(ObservableCollection<ImageSizeModel> availableSizes, ImageSizeModel model = null)
{
Models = availableSizes;
SelectedModel = model ?? (Models[0]);
}

private ImageSizeModel selectedModel;
public ImageSizeModel SelectedModel
{
get => selectedModel;
set => Set(ref selectedModel, value);
}

public ObservableCollection<ImageSizeModel> Models { get; }
= new ObservableCollection<ImageSizeModel>();
}



And the View for the Selector VM:

<UserControl 

x:Class=\"WpfListImageSizer.SelectorView\"

xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"

xmlns:m=\"clr-namespace:WpfListImageSizer\"

Height=\"300\" Width=\"200\">

<UserControl.Resources>
<DataTemplate DataType=\"{x:Type m:ImageSizeModel}\">
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat=\"{}{1} W x {2} H - ({0})\">
<Binding Path=\"Title\" />
<Binding Path=\"Width\" />
<Binding Path=\"Height\" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate
>
</UserControl.Resources>
<Grid>
<ListBox ItemsSource=\"{Binding Models}\"

SelectedItem=\"{Binding SelectedModel, Mode=TwoWay}\"/>
</Grid>
</UserControl>



And now for the VM for the MainWindow:

public class MainViewModel : ObservableBase, IViewModel 
{
public MainViewModel()
{
if (IsInDesignMode) return;

ImageSize = sizes[1];
selector = new SizeSelectorViewModel(sizes, ImageSize);
selector.PropertyChanged += Selector_PropertyChanged;

windowService.ShowWindow(selector);
}

private void Selector_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SizeSelectorViewModel.SelectedModel))
ImageSize = selector.SelectedModel;
}

private SizeSelectorViewModel selector;
private IWindowService windowService = new WindowService();

private readonly ObservableCollection<ImageSizeModel> sizes
= new ObservableCollection<ImageSizeModel>
{
new ImageSizeModel{ Width = 100, Height = 160, Title = \"Small\" },
new ImageSizeModel{ Width = 140, Height = 220, Title = \"Medium\" },
new ImageSizeModel{ Width = 180, Height = 280, Title = \"Large\" },
};

private ImageSizeModel imageSize;
public ImageSizeModel ImageSize
{
get => imageSize;
set => Set(ref imageSize, value);
}

public ObservableCollection< PersonModel> Staff { get; }
= new ObservableCollection<PersonModel>
{
new PersonModel
{
Firstname = \"Johnny\", Lastname = \"Appleseed\",
PhotoUrl=\"https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Dunn_Official_Headshot.jpg/220px-Dunn_Official_Headshot.jpg\"
},
new PersonModel
{
Firstname = \"Fred\", Lastname = \"Smith\",
PhotoUrl = \"http://vickmark.com/wp-content/uploads/2012/10/headshot-aon-g-web.jpg\"
},
new PersonModel
{
Firstname = \"Jose\", Lastname = \"Cordero\",
PhotoUrl = \"http://news.uga.edu/media/images/Jose-Cordero-230x348.jpg\"
},
new PersonModel
{
Firstname = \"Rod\", Lastname = \"Goodman\",
PhotoUrl = \"http://www.rodgoodmanphoto.com/img/s/v-3/p1313838186-3.jpg\"
}
};
}



And the MainWindow itself:

<Window 

x:Class=\"WpfListImageSizer.MainWindow\"

xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"

xmlns:vm=\"clr-namespace:WpfListImageSizer\"

xmlns:m=\"clr-namespace:WpfListImageSizer\"

Title=\"MainWindow\" Height=\"350\" Width=\"525\" WindowStartupLocation=\"CenterScreen\">

<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>

<Window.Resources>
<Style x:Key=\"NameStyle\" TargetType=\"{x:Type TextBlock}\">
<Setter Property=\"FontFamily\" Value=\"Segoe UI\"/>
<Setter Property=\"FontWeight\" Value=\"Light\"/> $b $b <Setter Property=\"FontSize\" Value=\"32\"/>
<Setter Property=\"Margin\" Value=\"0 0 0 10\"/>
</Style>

<Style x:Key=\"DetailsStyle\" TargetType=\"{x:Type StackPanel}\">
<Setter Property=\"Margin\" Value=\"20 0 0 0\"/>
<Setter Property=\"Grid.Column\" Value=\"1\"/>
<Setter Property=\"VerticalAlignment\" Value=\"Center\"/>
</Style>

<Style x:Key=\"FrameStyle\" TargetType=\"{x:Type Border}\">
<Setter Property=\"Margin\" Value=\"10\"/>
<Setter Property=\"Padding\" Value=\"10\"/>
<Setter Property=\"Background\" Value=\"GhostWhite\"/>
</Style>

<Style x:Key=\"PhotoStyle\" TargetType=\"{x:Type Image}\">
<Setter Property=\"Width\" Value=\"{Binding ElementName=Host, Path=DataContext.ImageSize.Width}\"/>
<Setter Property=\"Height\" Value=\"{Binding ElementName=Host, Path=DataContext.ImageSize.Height}\"/>
</Style>

<DataTemplate DataType=\"{x:Type m:PersonModel}\">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=\"Auto\"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>

<Border Style=\"{StaticResource FrameStyle}\">
<Image Source=\"{Binding PhotoUrl}\" Style=\"{StaticResource PhotoStyle}\"/>
</Border>
<StackPanel Style=\"{StaticResource DetailsStyle}\">
<TextBlock Text=\"{Binding Firstname}\" Style=\"{StaticResource NameStyle}\"/>
<TextBlock Text=\"{Binding Lastname}\" Style=\"{StaticResource NameStyle}\"/>
</StackPanel>
</Grid>
</DataTemplate
>

<Style TargetType=\"{x:Type ListBoxItem}\">
<Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\"/>
</Style>
</Window.Resources>

<Grid>
<ListBox x:Name=\"Host\" ItemsSource=\"{Binding Staff}\"

VirtualizingPanel.ScrollUnit=\"Pixel\"/>
</Grid>

</Window>



Right, all the code is out of th e way.



How it works:



1. MainViewModel preps the image size data and the default size. It then creates a Selector VM and passes the data to it and listens for any changes. We then pass the SElector VM to the Windows Service. The Windows service creates a new window, sets the DataContext to the Selector VM.



2. As we have defined in the App.Xaml the association of the VM with the VM, the Window’s Content is loaded with the associated View, the Listbox is filled, and the default selection is made.



3. When a selection is made in the Selector Window, the data bound SelectedModel is changed, the PropertyChanged event is triggered, the MainViewModel catches the event, updates the local image size property and the Xaml binding is updated. The Style for the Image is bound to the MainViewModel and updates the UI.



Whew, Task accomplished... Enjoy! :)



PS: I have not put any error handling into the code. I leave that to you! ;)


hello guys,

I have created listbox in wpf mainindow, that will display Images tile style that's perfect.
now I have one more window that will contain 3 option like small(160Height,100 Width), medium(220H, 140W), large(280H,180H) as radio button, and apply button,
once I select medium and click apply button then my listbox item size should be 220H, 140W. like for small adn large how to do this?
Below are my listbox.

<ListBox l:ListBoxSelector.Enabled="{Binding ElementName=UC,Path=MouseSelection,UpdateSourceTrigger=PropertyChanged}"

         FocusVisualStyle="{x:Null}" IsEnabled="{Binding ElementName=LoadingAdorner,Path=IsAdornerVisible,
         Converter={StaticResource BoolReverse},UpdateSourceTrigger=PropertyChanged}" 

         ItemsSource="{Binding ElementName=UC,Path=ThumbImages,IsAsync=True,UpdateSourceTrigger=PropertyChanged}"

         x:FieldModifier="public" Name="listBoxComposerThumbs" BorderBrush="Transparent"

         Background="{DynamicResource ThumbnailBackgroundColor}" Margin="5,48,5,10" Drop="listBoxComposerThumbs_Drop" 

         AllowDrop="True" SelectionMode="Extended" SelectionChanged="OnThumbViewSelectChanged"

         ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" 

         ScrollViewer.CanContentScroll="True" MouseDoubleClick="ThumbView_MouseDoubleClick"

         MouseRightButtonDown="ThumbView_MouseLeftBtnDown" MouseLeftButtonDown="ThumbView_MouseLeftBtnDown" 

         RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.EdgeMode="Aliased" 

         LayoutUpdated="listBoxComposerThumbs_LayoutUpdated" KeyDown="listBoxComposerThumbs_KeyDown">
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <EventSetter Event="ContextMenuOpening" Handler="listBoxComposerWorkSpace_ContextMenu"/>
        </Style>
    </ListBox.Style>
    <ListBox.ContextMenu>
        <ContextMenu Style="{x:Null}" >
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.CutMenu}" Foreground="Black" TextBlock.Foreground="Black" InputGestureText="Ctrl+X" IsEnabled="False" FontFamily="Segoe UI Regular" FontSize="12"/>
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.CopyMenu}"  Foreground="Black" TextBlock.Foreground="Black" InputGestureText="Ctrl+C" IsEnabled="False" FontFamily="Segoe UI Regular" FontSize="12"/>
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.PasteMenu}" Foreground="Black" TextBlock.Foreground="Black" Tag="P" Click="PasteBtn_Click"  InputGestureText="Ctrl+V" FontFamily="Segoe UI Regular" FontSize="12"/>
            <Separator/>
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.DeleteText}" Foreground="Black" TextBlock.Foreground="Black" InputGestureText="Del" IsEnabled="False" FontFamily="Segoe UI Regular" FontSize="12"/>
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.SelectAllMenu}" Foreground="Black" TextBlock.Foreground="Black" Tag="S" Click="SelectAllBtn_Click"  InputGestureText="Ctrl+A" FontFamily="Segoe UI Regular" FontSize="12"/>
            <Separator/>
            <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.InsertMenu}" Foreground="Black" TextBlock.Foreground="Black" Tag="I" Click="InsertBlankPageBtn_Click" InputGestureText="Ctrl+B" FontFamily="Segoe UI Regular" FontSize="12"/>
        </ContextMenu>
    </ListBox.ContextMenu>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid SizeChanged="scroll_SizeChanged" Columns="{Binding ElementName=UC, Path=TileColumns}" 

                         FocusVisualStyle="{x:Null}" VerticalAlignment="Top"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <Border>
                    <Border.Effect>
                        <DropShadowEffect BlurRadius="20" ShadowDepth="0" Opacity="0.8"   Color="Black"/>
                    </Border.Effect>
                    <Grid Background="White" HorizontalAlignment="Left">
                        <Grid x:Name="ListItemPanel" >
                            <Grid.Style>
                                <Style TargetType="Grid">
                                    <EventSetter Event="ContextMenuOpening" Handler="listBoxComposerThumbs_ContextMenu"/>
                                </Style>
                            </Grid.Style>
                            <Grid.ContextMenu>
                                <ContextMenu Style="{x:Null}" >
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.CutMenu}" Command="Cut" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Ctrl+X" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.CopyMenu}" Command="Copy" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Ctrl+C" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.PasteMenu}" Tag="P" Command="Paste" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Ctrl+V" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <Separator/>
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.DeleteText}" Command="Delete" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Del" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.SelectAllMenu}" Command="SelectAll" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Ctrl+A" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <Separator/>
                                    <MenuItem Style="{x:Null}" Header="{x:Static culture:Resources.InsertMenu}" Command="Pause" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" InputGestureText="Ctrl+B" FontFamily="Segoe UI Regular" FontSize="12"/>
                                    <Separator/>
                                    <MenuItem Style="{StaticResource MenuSelectPaper}" Header="{x:Static culture:Resources.SelectPSMenu}" Tag="{Binding BinNo,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" x:Name="SelectPaperMenu" FontFamily="Segoe UI Regular" FontSize="12"/>
                                </ContextMenu>
                            </Grid.ContextMenu>

                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>

                            <Rectangle x:Name="HeaderRect" Grid.Row="0" Fill="Red" Height="6"  

                                       Visibility="{Binding Path=BHdr,Converter={StaticResource BoolVisble},UpdateSourceTrigger=PropertyChanged}"/>
                            <!--<Image Grid.Row="1" Source="{Binding ThumbnailImage}" Stretch="Fill"  Height="{Binding Path=ImageHeight,Converter={StaticResource HeightConvert},ConverterParameter=260,UpdateSourceTrigger=PropertyChanged}"  Width="{Binding Path=ImageWidth,Converter={StaticResource WidthConvert},ConverterParameter=260,UpdateSourceTrigger=PropertyChanged}">-->
                            <Image Grid.Row="1" Source="{Binding ThumbnailImage}" Stretch="Fill"  Height="{Binding Path=RectHeight,UpdateSourceTrigger=PropertyChanged}" 

                                   Width="{Binding Path=RectWidth,UpdateSourceTrigger=PropertyChanged}">
                                    <Image.LayoutTransform>
                                    <RotateTransform Angle="{Binding RotateAngle,UpdateSourceTrigger=PropertyChanged}"/>
                                </Image.LayoutTransform>
                            </Image>
                            <Rectangle x:Name="FooterRect" Fill="Red" Grid.Row="2" Height="3"  Visibility="{Binding Path=BFtr,Converter={StaticResource BoolVisble},UpdateSourceTrigger=PropertyChanged}"/>
                            <TextBlock Text="{Binding BinNo}" Visibility="Collapsed"/>
                        </Grid>
                        
                    </Grid>
                </Border>

                <TextBlock Grid.Row="1" Foreground="{DynamicResource NofilesForegroundColor}" HorizontalAlignment="Center">
                        <Run x:Uid="DisplayPage" Text="{x:Static culture:Resources.DisplayPage}"/>
                         <Run Text="{Binding PageNumber}"/>
                </TextBlock>
            </Grid>
            
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ListBox.Resources>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
            <EventSetter Event="PreviewMouseLeftButtonUp" Handler="ListBoxItem_PreviewMouseLeftButtonUp"/>
            <EventSetter Event="Drop" Handler="ListBoxItem_Drop"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="AllowDrop" Value="True"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Padding" Value="0,0,0,0"/>
            <Setter Property="Margin" Value="10,10,10,0"/>                                    
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Grid Grid.Column="0" x:Name="GLeftBd" Visibility="{Binding ElementName=UC,Path=MouseDragVisibility,UpdateSourceTrigger=PropertyChanged}" Drop="GridDrop" DragOver="GridDragOver" DragLeave="GridDragLeave" DragEnter="GridDragEnter" Margin="-40,0,0,0" Background="#19FFFFFF">
                                <Border x:Name="LeftBd" Background="Black" Visibility="Collapsed" CornerRadius="2" Width="2" Margin="0,5,8,15" HorizontalAlignment="Right">
                                    <Border.Effect>
                                        <DropShadowEffect BlurRadius="8" ShadowDepth="0" Opacity="0.8" Color="Black"/>
                                    </Border.Effect>
                                </Border>
                            </Grid>
                            <Grid Grid.Column="1" x:Name="ThumbImageBaseGrid"  HorizontalAlignment="Center" VerticalAlignment="Center">
                                <ContentPresenter x:Name="ThumbContentHost" Margin="3"  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                <Rectangle x:Name="BackgroundRect" Fill="{x:Null}"  Opacity="0" Margin="0" Stroke="{DynamicResource ContentBorderBackgroundColor}" StrokeThickness="3"/>
                            </Grid>
                            <Grid Grid.Column="2" x:Name="GRightBd" Visibility="{Binding ElementName=UC,Path=MouseDragVisibility,UpdateSourceTrigger=PropertyChanged}" Drop="GridDrop" DragOver="GridDragOver" DragLeave="GridDragLeave" DragEnter="GridDragEnter" Margin="0,0,-40,0" Background="#19FFFFFF">
                                <Border x:Name="RightBd" Background="Black" Visibility="Collapsed" CornerRadius="2" Width="2" Margin="8,5,0,15" HorizontalAlignment="Left">
                                    <Border.Effect>
                                        <DropShadowEffect BlurRadius="8" ShadowDepth="0" Opacity="0.8" Color="Black"/>
                                    </Border.Effect>
                                </Border>
                            </Grid>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <!--<EventTrigger RoutedEvent="Loaded">
                                    <EventTrigger.Actions>
                                        <BeginStoryboard  Storyboard="{StaticResource LoadAnimation}"/>
                                    </EventTrigger.Actions>
                                </EventTrigger>
                                <EventTrigger RoutedEvent="Unloaded">
                                    <EventTrigger.Actions>
                                        <BeginStoryboard Storyboard="{StaticResource UnLoadAnimation}"/>
                                   </EventTrigger.Actions>
                                </EventTrigger>-->
                            <Trigger Property="IsSelected" Value="True">
                                <Setter TargetName="BackgroundRect" Property="Opacity" Value="1"/>
                                <!--<Setter TargetName="border" Property="BorderThickness" Value="0"/>
                                     <Setter TargetName="border" Property="BorderBrush" Value="Red"/>-->
                            </Trigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsSelected" Value="true"/>
                                    <Condition Property="Selector.IsSelectionActive" Value="false"/>
                                </MultiTrigger.Conditions>
                                <Setter TargetName="BackgroundRect" Property="Opacity" Value="1"/>
                            </MultiTrigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground" Value="Transparent"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="Transparent"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>
</ListBox>



What I have tried:

I googled but not getting any related solutions. pleas any one can suggest me how to solve this.

解决方案

I'll take a stab at what you want to do.

You're trying to dynamically change the size of an image from a selection list in another window. You're using Data Binding, so I'm going to guess that this is a MVVM project.

Firstly, being a MVVM project, ViewModels (VMs) can't directly reference UI objects like Windows however VMs can create other VMs. So we need a proxy service to launch a Selector Window using the associate VM:

public interface IViewModel
{

}

internal interface IWindowService
{
    void ShowWindow(IViewModel viewModel);
}

internal class WindowService : IWindowService
{
    public void ShowWindow(IViewModel viewModel)
        => (new Window
        {
            Content = viewModel,
            SizeToContent = SizeToContent.WidthAndHeight,
            WindowStartupLocation = WindowStartupLocation.CenterScreen
        }).Show();
}


For this to work, we need to set the DataTemplate in the App.XAML:

<Application

    x:Class="WpfListImageSizer.App"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:vm="clr-namespace:WpfListImageSizer"

    xmlns:vw="clr-namespace:WpfListImageSizer"

    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <DataTemplate DataType="{x:Type vm:SizeSelectorViewModel}">
            <vw:SelectorView/>
        </DataTemplate>
    </Application.Resources>
</Application>


The DataTemplate links the SelectorView to the SizeSelectorViewModel.
Next, as we are using Data Binding, we need to implement the INotifyPropertyChanged event handler for the data model and the VMs. So it is easier to create a base class that implements it:

public abstract class ObservableBase : INotifyPropertyChanged
{
    public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public bool IsInDesignMode => DesignerProperties.GetIsInDesignMode(new DependencyObject());
}


I've also added the IsInDesignMode into the base class. This is used to prevent the VS (Visual Studio) Designer from executing specific code in our project - VMs in this case.

Now we need our data models - one for the Image Size selection, and another for our dummy data to test with:

public class ImageSizeModel : ObservableBase
{
    private string title;
    public string Title
    {
        get => title;
        set => Set(ref title, value);
    }

    private double width;
    public double Width
    {
        get => width;
        set => Set(ref width, value);
    }

    private double height;
    public double Height
    {
        get => height;
        set => Set(ref height, value);
    }
}

public class PersonModel : ObservableBase
{
    private string firstname;
    public string Firstname
    {
        get => firstname;
        set => Set(ref firstname, value);
    }

    private string lastname;
    public string Lastname
    {
        get => lastname;
        set => Set(ref lastname, value);
    }

    private string photoUrl;
    public string PhotoUrl
    {
        get => photoUrl;
        set => Set(ref photoUrl, value);
    }
}



Now for our view models. First, we need the Selector VM:

public class SizeSelectorViewModel : ObservableBase, IViewModel
{
    public SizeSelectorViewModel()
    {

    }

    public SizeSelectorViewModel(ObservableCollection<ImageSizeModel> availableSizes, ImageSizeModel model = null)
    {
        Models = availableSizes;
        SelectedModel = model ?? (Models[0]);
    }

    private ImageSizeModel selectedModel;
    public ImageSizeModel SelectedModel
    {
        get => selectedModel;
        set => Set(ref selectedModel, value);
    }

    public ObservableCollection<ImageSizeModel> Models { get; }
        = new ObservableCollection<ImageSizeModel>();
}


And the View for the Selector VM:

<UserControl

    x:Class="WpfListImageSizer.SelectorView"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:m="clr-namespace:WpfListImageSizer"

    Height="300" Width="200">

    <UserControl.Resources>
        <DataTemplate DataType="{x:Type m:ImageSizeModel}">
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{1} W x {2} H - ({0})">
                        <Binding Path="Title" />
                        <Binding Path="Width" />
                        <Binding Path="Height" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </UserControl.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Models}"

                 SelectedItem="{Binding SelectedModel, Mode=TwoWay}"/>
    </Grid>
</UserControl>


And now for the VM for the MainWindow:

public class MainViewModel : ObservableBase, IViewModel
{
    public MainViewModel()
    {
        if (IsInDesignMode) return;

        ImageSize = sizes[1];
        selector = new SizeSelectorViewModel(sizes, ImageSize);
        selector.PropertyChanged += Selector_PropertyChanged;

        windowService.ShowWindow(selector);
    }

    private void Selector_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(SizeSelectorViewModel.SelectedModel))
            ImageSize = selector.SelectedModel;
    }

    private SizeSelectorViewModel selector;
    private IWindowService windowService = new WindowService();

    private readonly ObservableCollection<ImageSizeModel> sizes
        = new ObservableCollection<ImageSizeModel>
        {
            new ImageSizeModel{ Width = 100, Height = 160, Title = "Small" },
            new ImageSizeModel{ Width = 140, Height = 220, Title = "Medium" },
            new ImageSizeModel{ Width = 180, Height = 280, Title = "Large" },
        };

    private ImageSizeModel imageSize;
    public ImageSizeModel ImageSize
    {
        get => imageSize;
        set => Set(ref imageSize, value);
    }

    public ObservableCollection<PersonModel> Staff { get; }
    = new ObservableCollection<PersonModel>
    {
        new PersonModel
        {
            Firstname = "Johnny", Lastname = "Appleseed",
            PhotoUrl="https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Dunn_Official_Headshot.jpg/220px-Dunn_Official_Headshot.jpg"
        },
        new PersonModel
        {
            Firstname = "Fred", Lastname = "Smith",
            PhotoUrl = "http://vickmark.com/wp-content/uploads/2012/10/headshot-aon-g-web.jpg"
        },
        new PersonModel
        {
            Firstname = "Jose", Lastname = "Cordero",
            PhotoUrl = "http://news.uga.edu/media/images/Jose-Cordero-230x348.jpg"
        },
        new PersonModel
        {
            Firstname = "Rod", Lastname = "Goodman",
            PhotoUrl = "http://www.rodgoodmanphoto.com/img/s/v-3/p1313838186-3.jpg"
        }
    };
}


And the MainWindow itself:

<Window

    x:Class="WpfListImageSizer.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:vm="clr-namespace:WpfListImageSizer"

    xmlns:m="clr-namespace:WpfListImageSizer"

    Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen">

    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>

    <Window.Resources>
        <Style x:Key="NameStyle" TargetType="{x:Type TextBlock}">
            <Setter Property="FontFamily" Value="Segoe UI"/>
            <Setter Property="FontWeight" Value="Light"/>
            <Setter Property="FontSize" Value="32"/>
            <Setter Property="Margin" Value="0 0 0 10"/>
        </Style>

        <Style x:Key="DetailsStyle" TargetType="{x:Type StackPanel}">
            <Setter Property="Margin" Value="20 0 0 0"/>
            <Setter Property="Grid.Column" Value="1"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>

        <Style x:Key="FrameStyle" TargetType="{x:Type Border}">
            <Setter Property="Margin" Value="10"/>
            <Setter Property="Padding" Value="10"/>
            <Setter Property="Background" Value="GhostWhite"/>
        </Style>

        <Style x:Key="PhotoStyle" TargetType="{x:Type Image}">
            <Setter Property="Width" Value="{Binding ElementName=Host, Path=DataContext.ImageSize.Width}"/>
            <Setter Property="Height" Value="{Binding ElementName=Host, Path=DataContext.ImageSize.Height}"/>
        </Style>

        <DataTemplate DataType="{x:Type m:PersonModel}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>

                <Border Style="{StaticResource FrameStyle}">
                    <Image Source="{Binding PhotoUrl}" Style="{StaticResource PhotoStyle}"/>
                </Border>
                <StackPanel Style="{StaticResource DetailsStyle}">
                    <TextBlock Text="{Binding Firstname}" Style="{StaticResource NameStyle}"/>
                    <TextBlock Text="{Binding Lastname}"  Style="{StaticResource NameStyle}"/>
                </StackPanel>
            </Grid>
        </DataTemplate>
        
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </Window.Resources>

    <Grid>
        <ListBox x:Name="Host" ItemsSource="{Binding Staff}"

                 VirtualizingPanel.ScrollUnit="Pixel"/>
    </Grid>

</Window>


Right, all the code is out of the way.

How it works:

1. MainViewModel preps the image size data and the default size. It then creates a Selector VM and passes the data to it and listens for any changes. We then pass the SElector VM to the Windows Service. The Windows service creates a new window, sets the DataContext to the Selector VM.

2. As we have defined in the App.Xaml the association of the VM with the VM, the Window's Content is loaded with the associated View, the Listbox is filled, and the default selection is made.

3. When a selection is made in the Selector Window, the data bound SelectedModel is changed, the PropertyChanged event is triggered, the MainViewModel catches the event, updates the local image size property and the Xaml binding is updated. The Style for the Image is bound to the MainViewModel and updates the UI.

Whew, Task accomplished... Enjoy! :)

PS: I have not put any error handling into the code. I leave that to you! ;)


这篇关于如何在C#WPF中动态更改列表框项目大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆