就在昨天,我开始探索mvvm wpf,所以,如果我做错了什么,请不要打我!我想通过单击按钮来改变stackpanel的可见性。我这里有个问题我的代码:
视图模型库
public abstract class ViewModelBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
MyCommand
public abstract class ViewModelBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
型号
class MyModel
{
public Visibility myVisibility;
}
视图模型1
public class MMViewModel: ViewModelBase
{
public System.Windows.Visibility MyVisibility
{
get { return M.myVisibility; }
set
{
M.myVisibility = value;
OnPropertyChanged(nameof(MyVisibility));
}
}
}
视图模型2
private ICommand myCommand;
public ObservableCollection<MMViewModel> mm1;
public ObservableCollection<MMViewModel> MM1
{
get { return mm1; }
set
{
mm1 = value;
OnPropertyChanged(nameof(MM1));
}
}
public ICommand MyButtonClickCommand
{ get { return myCommand; }
set { myCommand = value; }
}
public MyVievModel()
{
MM1 = new ObservableCollection<MMViewModel>();
MM1.Add(new MMViewModel
{
MyVisibility = Visibility.Visible
});
myCommand = new MyCommand(ChangeVis, ToEvaluate);
//LabelCommand = new MyVievModel(o => MainLabelClick("MainButton"));
}
private void ChangeVis(object context)
{
MM1[0].MyVisibility = Visibility.Hidden;
}
private bool ToEvaluate(object context)
{
return true;
}
XAML
<StackPanel>
<ItemsControl ItemsSource="{Binding Path=MM1}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border BorderBrush="Blue" BorderThickness="2"
Grid.ColumnSpan="2"/>
<StackPanel>
<Button Grid.Column="0" VerticalAlignment="Center"
Content="What is Netflix?"
FontSize="30" Foreground="White" Command="{Binding
MyButtonClickCommand}">
</Button>
<TextBlock Grid.Column="1" HorizontalAlignment="Right"
Text="+"
FontSize="60" Foreground="White">
</TextBlock>
<StackPanel Margin="0 5 0 0" Visibility="{Binding ChangeVis,
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBlock Foreground="White"
FontSize="20">Text1<LineBreak/> Text1 continue</TextBlock>
<TextBlock Margin="0 20 0 0" Foreground="White"
FontSize="20">
Text2
</TextBlock>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
如果你有一些关于如何改进我的代码的提示-这将是非常好的!感谢您的提示和评论!
1条答案
按热度按时间mklgxw1f1#
最简单的MVVM解决方案是命名
StackPanel
并将其可见性从代码隐藏更改为:如果需要视图模型类中的值,可以将
Visibilty
属性绑定到bool
属性,并使用BooleanToVisibilityConverter
类:MainWindow.xaml
MainWindow.xaml.cs
MainViewModel.cs