大家好我有一个列表视图,由ObservableCollection填充。现在我想从列表中获取所选项目的值并存储它。我怎么能做到这一点?
这是我的ViewModel:
public StopViewModel(IGrtrService grtrService)
{
Argument.IsNotNull(() => grtrService);
_grtrService = grtrService;
AllStops = _grtrService.LoadStop();
Stop_Line = _grtrService.LoadLines();
SearchCollection = new Command(OnSearchPressed);
}
public ObservableCollection<Stop> AllStopsCollection // Must be property or DP to be bound!
{
get { return AllStops; }
set
{
if (Equals(value, AllStops)) return;
AllStops = value;
}
}
public Grtr Grtr
{
get { return GetValue<Grtr>(GrtrProperty); }
set { SetValue(GrtrProperty, value); }
}
public static readonly PropertyData GrtrProperty = RegisterProperty("Grtr", typeof(Grtr));
}
在XAML文件中,我有以下代码:
<catel:StackGrid x:Name="LayoutRoot">
<catel:StackGrid.ColumnDefinitions>
<ColumnDefinition />
</catel:StackGrid.ColumnDefinitions>
<catel:StackGrid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</catel:StackGrid.RowDefinitions>
<ToolBarTray Grid.Row="0" VerticalAlignment="Top" Background="Azure">
<ToolBar>
<TextBox Width="150" Text="{Binding Path=SearchValue}" />
<Button Content="Search" Command="{Binding SearchCollection}" />
<Button Content="Pass Object" Command="{Binding SearchCollection}" />
</ToolBar>
</ToolBarTray>
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop}" />
</catel:StackGrid>
答案 0 :(得分:2)
由于您使用的是Catel,它会自动处理您的更改通知。只需定义此属性:
public Stop SelectedStop
{
get { return GetValue<Stop>(SelectedStopProperty); }
set { SetValue(SelectedStopProperty, value); }
}
public static readonly PropertyData SelectedStopProperty = RegisterProperty("SelectedStop", typeof(Stop));
它将被设置为值。
专业提示:如果您使用Catel.Fody,则可以写下:
public Stop SelectedStop { get; set; }
,它将自动转换为最终的Catel属性,如上所述。
答案 1 :(得分:0)
正如我从评论中看到的那样,您无法弄清楚如何将列表的所选项目绑定到属性。首先,您需要在视图模型中创建相应的属性:
public Stop SelectedStop
{
get
{
return _selectedStop;
}
set
{
if (Equals(value, _selectedStop)) return;
_selectedStop = value;
}
}
确保您实施INotifyPropertyChanged界面,并且您的财产正在筹集&#34; OnPropertyChanged&#34;什么时候改变了。 对于列表框,您应该设置:
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop, Mode=TwoWay}" />
答案 2 :(得分:0)
在ViewModel中:
private stop _selectedStop;
public Stop SelectedStop
{
get
{
return _selectedStop;
}
set
{
if (_selectedStop!= value)
_selectedStop = value;
OnPropertyChanged("SelectedStop"); //U should implement this method using INotifyPropertyChanged
}
}
在你的窗口(XAML)中,将Binding的模式设置为TwoWay:
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop, Mode=twoWay}" />