我有一个带有“选择”按钮的用户控件上显示的设备列表。列表数据来自父ViewModel,我希望它能让用户选择他们想要的设备,点击“选择”按钮,然后按钮命令返回所选的设备。
此外,我想要一个单选按钮或矩形,它可以改变颜色来表示并与活动选择同步工作(例如,您可以选择单选按钮并选择ListItem,或者单击ListItem并选择单选按钮)。
我让绑定工作到ListBox,这样它就可以显示设备,但是我不知道如何让绑定工作,所以选择返回。
以下是我正在使用的内容:
查看模型
// Props
private MutlipleAttachedDevicesModel _selectedDevice;
public MutlipleAttachedDevicesModel SelectedDevice
{
get { return _selectedDevice; }
set
{
_selectedDevice = value;
RaisePropertyChanged();
}
}
// Methods
public void DisplaySelectDevices()
{
// Create new display
DeviceSelectionVM = new DeviceSelectionViewModel();
CurrentView = DeviceSelectionVM;
// Populate Device List
DeviceList = PopulateDeviceList();
}
private void CreateDummyData()
{
Random r = new Random();
var count = 0;
// make a max of 3 devices
for(var i = 0; i < 3; i++)
{
DeviceList.Add(new MutlipleAttachedDevicesModel()
{
Name = "SP-2 Super Processor",
Serial = $"SP2-00"+ r.Next(100).ToString(),
IsSelection = false,
WasUpdated = false
});
// First Device defaults to selected
if (i == 0)
DeviceList[i].IsSelection = true;
count++;
}
}
private void SelectTargetDevice(object selection)
{
// Display Target Device
var count = DeviceList.Count;
for (var i=0; i<=count; i++)
{
if (DeviceList[i].IsSelection == true)
{
SelectedDevice = DeviceList[i];
break;
}
}
Trace.WriteLine("Selection was "+ SelectedDevice.Serial);
}ListBox
<ListBox x:Name="MultipleDeviceSelectionList"
ItemsSource="{Binding DataContext.DeviceList,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page}}"
SelectedItem="{Binding IsSelection,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page},
Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<RadioButton GroupName="radio"
IsChecked="{Binding IsSelection}" />
<TextBlock Text="{Binding Name}"/>
<StackPanel>
<TextBlock>
Serial #:
</TextBlock>
<TextBlock Text="{Binding Serial}"/>
</StackPanel>
<TextBlock Visibility="{Binding WasUpdated,
Converter={StaticResource BoolToVisConverter},
FallbackValue=Hidden}">
Up To Date
</TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Command="{Binding DataContext.SelectButtonCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Page}}">
Select
</Button>我还尝试了其他方法,比如尝试将单选按钮双向绑定到列表框的SelectedItem属性,但老实说,复杂的绑定仍然让我感到困惑。我需要做什么才能使单选按钮与列表选择保持一致,并正确返回列表选择?
发布于 2019-12-11 18:30:48
更改您的ListView SelectedItem绑定。您希望绑定到SelectedDevice属性。
<ListBox x:Name="MultipleDeviceSelectionList"
ItemsSource="{Binding DataContext.DeviceList,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page}}"
SelectedItem="{Binding SelectedDevice,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page},
Mode=TwoWay}">但也许你真的应该检查属性的类型是否正确,因为"MutlipleAttachedDevicesModel“看起来不像是单个设备的模型。此外,我不确定您是否需要该绑定上的RelativeSource。
https://stackoverflow.com/questions/59276841
复制相似问题