[英]WPF: One way binding to source from ListBox
我有一个ListBox,其ItemSource是一个列表,其中X定义为:
public class X
{
public string FullPath { get; set; }
}
我的ViewModel是
public class ViewModel
{
public List<X> MyList { get; set; }
public X MyItem { get; set; }
public ViewModel()
{
MyList = new List<X>
{
new X { FullPath = "q:\\temp\\x1.png"},
new X { FullPath = "q:\\temp\\x2.png"}
};
}
}
和XAML:
<Window x:Class="Bind1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Bind1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<StackPanel>
<Image Source="{Binding MyItem.FullPath, Mode=OneWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="None"/>
<ListBox ItemsSource="{Binding MyList}"
SelectedItem="{Binding MyItem, Mode=OneWayToSource}"
SelectionMode="Single">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FullPath}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
当我在ListBox中使用键盘的向上和向下箭头时,此功能有效(来自ListBox中所选路径的图像显示在<Image>中)。 但是,当我用鼠标单击一个项目时,在列表框中没有选择我单击的项目(鼠标单击无效)。 正确的图像会非常短暂地显示在图像中(几分之一秒),然后显示原始图像。 我究竟做错了什么?
由于您正在使用StackPanel
,因此当ListBox
的Image
随选择更改而更改时, Image
控件的大小可能会更改,因此ListBox
的位置也会更改。
这种情况可能会导致以下效果:放开鼠标按钮时,单击的列表项可能与项目位置不同,因此与单击的列表项不同。
有许多解决方法,例如,固定Image
控件的大小,使用Grid
定义布局或将Image
放在StackPanel
的ListBox
之后
我可以重现该问题,您可以固定图像大小或将图像控件移到列表框下方。 我同意埃文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.