当ListView在UWP中不包含MVVM项时显示消息
这是我的第一个MVVM项目,我需要编写代码来操作视图中的控件,但不知何故,代码似乎比实际情况复杂得多 我发现很难完全理解MVVM,也很难决定什么时候可以把东西放在代码后面 基本上,我的问题是,我想显示一条消息,告诉用户listview是空的,而它绑定到的ObservableCollection不包含任何项。其想法是在视图中有一个TextBlock,并且只有在没有要显示的项目时(在用户创建项目之前和删除所有项目之后),才将其visibility属性设置为Visible 我无法使用此解决方案,因为UWP不支持BooleanToVisibilityConverter: 查看:当ListView在UWP中不包含MVVM项时显示消息,listview,winrt-xaml,win-universal-app,windows-10-universal,Listview,Winrt Xaml,Win Universal App,Windows 10 Universal,这是我的第一个MVVM项目,我需要编写代码来操作视图中的控件,但不知何故,代码似乎比实际情况复杂得多 我发现很难完全理解MVVM,也很难决定什么时候可以把东西放在代码后面 基本上,我的问题是,我想显示一条消息,告诉用户listview是空的,而它绑定到的ObservableCollection不包含任何项。其想法是在视图中有一个TextBlock,并且只有在没有要显示的项目时(在用户创建项目之前和删除所有项目之后),才将其visibility属性设置为Visible 我无法使用此解决方案,因为U
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EventMaker3000.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModel="using:EventMaker3000.ViewModel"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
x:Class="EventMaker3000.View.EventPage"
mc:Ignorable="d">
<Page.BottomAppBar>
<CommandBar>
<CommandBar.Content>
<Grid/>
</CommandBar.Content>
<AppBarButton Icon="Delete" Label="Delete" IsEnabled="{Binding DeletebuttonEnableOrNot}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction/>
<Core:InvokeCommandAction Command="{Binding DeleteEventCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
<AppBarButton Icon="Add" Label="Add">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction TargetPage="EventMaker3000.View.CreateEventPage"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
<Page.DataContext>
<ViewModel:EventViewModel/>
</Page.DataContext>
<Grid Background="WhiteSmoke">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!--Header-->
<TextBlock
Text="Events"
Foreground="Black"
Margin="0,20,0,0"
Style="{ThemeResource HeaderTextBlockStyle}"
HorizontalAlignment="center"
VerticalAlignment="Center"/>
<ListView
ItemsSource="{Binding EventCatalogSingleton.Events, Mode=TwoWay}"
SelectedItem="{Binding SelectedEvent, Mode=TwoWay}"
Grid.Row="1"
Background="WhiteSmoke"
Padding="0,30,0,0">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction Command="{Binding EnableOrNotCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Center" Margin="5,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0"
Grid.Row="0"
Margin="5"
Text="{Binding Name, Mode=TwoWay}"
Style="{ThemeResource TitleTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="1"
Grid.Row="1"
Margin="5"
Text="{Binding Place, Mode=TwoWay}"
HorizontalAlignment="Right"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="2"
Margin="5"
Text="{Binding Description, Mode=TwoWay}"
Style="{ThemeResource BodyTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="1"
Margin="5"
Text="{Binding DateTime, Mode=TwoWay}"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<!--Sets each listview item to stretch-->
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<!-- TextBlock for empty list view-->
<TextBlock
Grid.Row="1"
Margin="5,5,5,5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="You have no events"
Style="{StaticResource BaseTextBlockStyle}"
Visibility="{Binding TextBlockVisibility}"/>
</Grid>
</Page>
Singleton:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EventMaker3000.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModel="using:EventMaker3000.ViewModel"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
x:Class="EventMaker3000.View.EventPage"
mc:Ignorable="d">
<Page.BottomAppBar>
<CommandBar>
<CommandBar.Content>
<Grid/>
</CommandBar.Content>
<AppBarButton Icon="Delete" Label="Delete" IsEnabled="{Binding DeletebuttonEnableOrNot}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction/>
<Core:InvokeCommandAction Command="{Binding DeleteEventCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
<AppBarButton Icon="Add" Label="Add">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction TargetPage="EventMaker3000.View.CreateEventPage"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
<Page.DataContext>
<ViewModel:EventViewModel/>
</Page.DataContext>
<Grid Background="WhiteSmoke">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!--Header-->
<TextBlock
Text="Events"
Foreground="Black"
Margin="0,20,0,0"
Style="{ThemeResource HeaderTextBlockStyle}"
HorizontalAlignment="center"
VerticalAlignment="Center"/>
<ListView
ItemsSource="{Binding EventCatalogSingleton.Events, Mode=TwoWay}"
SelectedItem="{Binding SelectedEvent, Mode=TwoWay}"
Grid.Row="1"
Background="WhiteSmoke"
Padding="0,30,0,0">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction Command="{Binding EnableOrNotCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Center" Margin="5,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0"
Grid.Row="0"
Margin="5"
Text="{Binding Name, Mode=TwoWay}"
Style="{ThemeResource TitleTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="1"
Grid.Row="1"
Margin="5"
Text="{Binding Place, Mode=TwoWay}"
HorizontalAlignment="Right"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="2"
Margin="5"
Text="{Binding Description, Mode=TwoWay}"
Style="{ThemeResource BodyTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="1"
Margin="5"
Text="{Binding DateTime, Mode=TwoWay}"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<!--Sets each listview item to stretch-->
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<!-- TextBlock for empty list view-->
<TextBlock
Grid.Row="1"
Margin="5,5,5,5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="You have no events"
Style="{StaticResource BaseTextBlockStyle}"
Visibility="{Binding TextBlockVisibility}"/>
</Grid>
</Page>
公共类事件目录单例
{
私有静态EventCatalogSingleton\u实例
private EventCatalogSingleton()
{
Events = new ObservableCollection<Event>();
// Creates instances of events and adds it to the observable collection.
LoadEventAsync();
}
//Checks if an instance already exists, if not it will create one. Makes sure we only have one instance
public static EventCatalogSingleton getInstance()
{
if (_instance != null)
{
return _instance;
}
else
{
_instance = new EventCatalogSingleton();
return _instance;
}
}
// Creates the observable collection
public ObservableCollection<Event> Events { get; set; }
public void AddEvent(Event newEvent)
{
Events.Add(newEvent);
PersistencyService.SaveEventsAsJsonAsync(Events);
}
public void AddEvent(int id, string name, string description, string place, DateTime date)
{
Events.Add(new Event(id, name, description, place, date));
PersistencyService.SaveEventsAsJsonAsync(Events);
}
public void RemoveEvent(Event myEvent)
{
Events.Remove(myEvent);
PersistencyService.SaveEventsAsJsonAsync(Events);
}
public async void LoadEventAsync()
{
var events = await PersistencyService.LoadEventsFromJsonAsync();
if (events != null)
foreach (var ev in events)
{
Events.Add(ev);
}
}
private EventCatalogSingleton()
{
事件=新的ObservableCollection();
//创建事件实例并将其添加到可观察集合。
LoadEventAsync();
}
//检查实例是否已经存在,如果不存在,它将创建一个。确保我们只有一个实例
公共静态事件目录Singleton getInstance()
{
如果(_实例!=null)
{
返回_实例;
}
其他的
{
_实例=新的EventCatalogSingleton();
返回_实例;
}
}
//创建可观察的集合
公共ObservableCollection事件{get;set;}
公共无效添加事件(事件newEvent)
{
Events.Add(newEvent);
PersistencyService.SaveEventsAsJsonAsync(事件);
}
public void AddEvent(int-id、字符串名称、字符串描述、字符串位置、日期时间)
{
添加(新事件(id、名称、描述、地点、日期));
PersistencyService.SaveEventsAsJsonAsync(事件);
}
公共无效删除事件(事件myEvent)
{
移除(myEvent);
PersistencyService.SaveEventsAsJsonAsync(事件);
}
公共异步void LoadEventAsync()
{
var events=await PersistencyService.LoadEventsFromJsonAsync();
如果(事件!=null)
foreach(事件中的var ev)
{
事件。添加(ev);
}
}
}
处理程序:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EventMaker3000.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModel="using:EventMaker3000.ViewModel"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
x:Class="EventMaker3000.View.EventPage"
mc:Ignorable="d">
<Page.BottomAppBar>
<CommandBar>
<CommandBar.Content>
<Grid/>
</CommandBar.Content>
<AppBarButton Icon="Delete" Label="Delete" IsEnabled="{Binding DeletebuttonEnableOrNot}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction/>
<Core:InvokeCommandAction Command="{Binding DeleteEventCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
<AppBarButton Icon="Add" Label="Add">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Click">
<Core:NavigateToPageAction TargetPage="EventMaker3000.View.CreateEventPage"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</AppBarButton>
</CommandBar>
</Page.BottomAppBar>
<Page.DataContext>
<ViewModel:EventViewModel/>
</Page.DataContext>
<Grid Background="WhiteSmoke">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!--Header-->
<TextBlock
Text="Events"
Foreground="Black"
Margin="0,20,0,0"
Style="{ThemeResource HeaderTextBlockStyle}"
HorizontalAlignment="center"
VerticalAlignment="Center"/>
<ListView
ItemsSource="{Binding EventCatalogSingleton.Events, Mode=TwoWay}"
SelectedItem="{Binding SelectedEvent, Mode=TwoWay}"
Grid.Row="1"
Background="WhiteSmoke"
Padding="0,30,0,0">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction Command="{Binding EnableOrNotCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Center" Margin="5,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0"
Grid.Row="0"
Margin="5"
Text="{Binding Name, Mode=TwoWay}"
Style="{ThemeResource TitleTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="1"
Grid.Row="1"
Margin="5"
Text="{Binding Place, Mode=TwoWay}"
HorizontalAlignment="Right"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="2"
Margin="5"
Text="{Binding Description, Mode=TwoWay}"
Style="{ThemeResource BodyTextBlockStyle}" Foreground="Black"/>
<TextBlock Grid.Column="0"
Grid.Row="1"
Margin="5"
Text="{Binding DateTime, Mode=TwoWay}"
Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<!--Sets each listview item to stretch-->
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<!-- TextBlock for empty list view-->
<TextBlock
Grid.Row="1"
Margin="5,5,5,5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="You have no events"
Style="{StaticResource BaseTextBlockStyle}"
Visibility="{Binding TextBlockVisibility}"/>
</Grid>
</Page>
公共类事件处理程序
{
public EventViewModel EventViewModel{get;set;}
公共事件处理程序(EventViewModel EventViewModel)
{
EventViewModel=EventViewModel;
}
public void CreateEvent()
{
EventViewModel.EventCatalogSingleton.AddEvent(EventViewModel.Id,EventViewModel.Name,EventViewModel.Description,EventViewModel.Place,DateTimeConverter.DateTimeOffsetAndTimeSetToDateTime(EventViewModel.Date,EventViewModel.Time));
}
私有void DeleteEvent()
{
EventViewModel.EventCatalogSingleton.Events.Remove(EventViewModel.SelectedEvent);
}
//删除前提示用户的确认框
公共异步void getDeleteConfirmationSync()
{
MessageDialog msgbox=newmessagedialog(“您确定要永久删除此事件吗?”,“删除事件”);
msgbox.Commands.Add(新UICommand
{
Label=“是”,
调用=命令=>DeleteEvent()
}
);
msgbox.Commands.Add(新UICommand
{
Label=“否”,
}
);
msgbox.DefaultCommandIndex=1;
msgbox.CancelCommandIndex=1;
msgbox.Options=MessageDialogOptions.AcceptUserInputAfterDelay;
等待msgbox.ShowAsync();
}
public void EnableOrNot()
{
EventViewModel.DeletebuttonEnableOrNot=EventViewModel.DeletebuttonEnableOrNot=true;
}
public void TextBlockVisibility()
{
if(EventViewModel.EventCatalogSingleton.Events.Count<1)
{
EventViewModel.TextBlockVisibility=EventViewModel.TextBlockVisibility=“可见”;
}
}
}
它包含了很多代码,我知道——我不知道应该省略什么。
我包括了当我在listview中选择了一个项目时启用删除按钮的代码——这很好
为什么删除listview中的所有项目后视图中的TextBlock不显示?为了更改视图中控件的外观和其他内容,我真的需要在viewmodel中添加属性和ICommand吗?我已经成功地在StackPanel中为我这样的项目添加了可见性绑定 cs型
Visibility showPanel = Visibility.Collapsed;
public Visibility ShowPanel
{
get
{
return showPanel;
}
set
{
showPanel = value;
NotifyPropertyChanged("ShowPanel");
}
}
XAML
首先,您希望尽最大努力在视图和视图模型之间保持清晰的关注点分离。因此,尽量不要包含特定于UI的类型,如
可见性
和消息对话框
。您可以为负责显示对话框的MessageDialog
创建一个界面,然后将其传递给视图模型
其次,您应该准备编写自己的值转换器(BooleanToVisibilityConverter
),如下所示:
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value,
Type targetType, object parameter, string language)
{
bool isVisible = (bool)value;
return isVisible ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value,
Type targetType, object parameter, string language)
{
return (Visibility)value == Visibility.Visible;
}
}
并在您的视图中这样使用它:
<Page
xmlns:converters="using:MyApp.Whatever">
<Page.Resources>
<converters:BooleanToVisibilityConverter x:Key="converter"/>
</Page.Resources>
<TextBlock
Visibility="{Binding HasNoItems, Mode=TwoWay,
Converter={StaticResource converter}}">
</TextBlock>
</Page>
有趣的是,我和Daren May刚刚在微软虚拟学院专门教授了一门免费课程。这对你来说可能是一个很好的资源。看视频#2@13分钟 看看这个简单的方法: 使用此代码:
class VisibleWhenZeroConverter : IValueConverter
{
public object Convert(object v, Type t, object p, string l) =>
Equals(0d, (double)v) ? Visibility.Visible : Visibility.Collapsed;
public object ConvertBack(object v, Type t, object p, string l) => null;
}
这个XAML:
<StackPanel.Resources>
<cvt:VisibleWhenZeroConverter x:Name="VisibleWhenZeroConverter" />
</StackPanel.Resources>
<ListView ItemsSource="{x:Bind Items}" x:Name="MyList">
<ListView.Header>
<TextBlock Visibility="{Binding Items.Count, ElementName=MyList,
Converter={StaticResource VisibleWhenZeroConverter}}">
<Run Text="There are no items." />
</TextBlock>
</ListView.Header>
</ListView>
有道理吗?我希望如此
附:这正好回答了你问题的标题。希望能有帮助
祝你好运 您是否正确实现了INotifyProperty更改?
public bool HasNoItems
{
get { return this.hasNoItems; }
set { this.hasNoItems = value; OnPropertyChanged(); }
}
class VisibleWhenZeroConverter : IValueConverter
{
public object Convert(object v, Type t, object p, string l) =>
Equals(0d, (double)v) ? Visibility.Visible : Visibility.Collapsed;
public object ConvertBack(object v, Type t, object p, string l) => null;
}
<StackPanel.Resources>
<cvt:VisibleWhenZeroConverter x:Name="VisibleWhenZeroConverter" />
</StackPanel.Resources>
<ListView ItemsSource="{x:Bind Items}" x:Name="MyList">
<ListView.Header>
<TextBlock Visibility="{Binding Items.Count, ElementName=MyList,
Converter={StaticResource VisibleWhenZeroConverter}}">
<Run Text="There are no items." />
</TextBlock>
</ListView.Header>
</ListView>