WPF的所有绑定

一、静态绑定
1、新建一个资源字典ButtonStyle

 <Style x:Key="btn" TargetType="Button">
     <Setter Property="Width" Value="200"/>
     <Setter Property="Height" Value="30"/>
     <Setter Property="FontSize" Value="18"/>
     <Setter Property="Foreground" Value="Red"/>
 </Style>

在App.xaml引入

 <ResourceDictionary Source="ButtonStyle.xaml" />

2、新建一个静态类和非静态类

 public static class RegionName
 {
     public static string Name { get; set; } = "静态绑定";
 }

 public class Region 
 {
     public string Name { get; set; } = "绑定";
 }

3、将这三种使用静态的不同形式在前端绑定

 <StackPanel Margin="20">
     <TextBlock Text="{x:Static local:RegionName.Name}" Margin="10" />
     <TextBlock Text="{Binding Name,Source={StaticResource region}}" Margin="10" />
     <Button Style="{StaticResource btn}" Margin="10" Content="静态按钮"/>
 </StackPanel>

4、关于TextBlock的绑定
一般情况下TextBlock只用于绑定文本,不能触发命令绑定,但是我们有多种形式可以实现TextBlock绑定命令
4-1、使用 xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

 <i:Interaction.Triggers>
     <i:EventTrigger EventName="MouseDown">
         <i:InvokeCommandAction Command="{Binding LoadedAsideCommand}" />
     </i:EventTrigger>
 </i:Interaction.Triggers>

4-2、
你可以通过将 TextBlock 放在一个支持 InputBindings 的容器控件中,比如 Border 或 Grid,然后在该容器上定义 MouseBinding 来间接实现这个功能。当容器控件捕获到鼠标事件时,你可以在相应的事件处理器中对 TextBlock 进行操作

 <Border Width="200" Height="50" Background="SkyBlue" Cursor="Hand">
     <Border.InputBindings>
         <MouseBinding MouseAction="LeftClick" Command="{Binding ClickCommand}"/>
     </Border.InputBindings>
     <TextBlock Text="Click Me!" HorizontalAlignment="Center" VerticalAlignment="Center"/>
 </Border>

5-1、绑定父类本身为自己的参数,这种写法不常见

 <StackPanel Grid.Row="1" Orientation="Horizontal" x:Name="stack">
            <StackPanel x:Name="stackChild">
                <Button Width="200" Height="30" Command="{Binding OpenCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=StackPanel}}"/>
            </StackPanel>
        </StackPanel>
		  public class MainWindowViewModel:BindableBase
    {

        public MainWindowViewModel()
        {
            OpenCommand = new DelegateCommand<object>(Execute,CanExecute);
        }

        private bool CanExecute(object obj)
        {
            return true;
        }

        private bool _isChecked=false;

        public bool IsChecked
        {
            get => _isChecked;
            set => SetProperty(ref _isChecked,value);
        }

        public void Execute(object obj)
        {
            if (obj is StackPanel stackPanel)
            {
                MessageBox.Show(stackPanel.Name);
            }
        }
        public ICommand OpenCommand { get; set; }
    }

虽然我嵌套了两层StackPanel,但是打印只会打印最近父类,如果要打印外围祖先类,需要使用使用 FindAncestors 扩展方法来查找更高层级的祖先

CommandParameter="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource FindAncestorsConverter}, ConverterParameter={x:Type local:MainWindow}}"

这里,FindAncestorsConverter 是一个自定义的 IValueConverter,它能够根据传入的类型参数,沿着元素树向上查找特定类型的祖先。
6-1、绑定自身,这种写法更不常见

 <StackPanel >
                <Button Background="AliceBlue" Width="200" Height="30" Command="{Binding OpenCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
            </StackPanel>
			  public void Execute(object obj)
        {
            if (obj is Button button)
            {
                button.Background = new SolidColorBrush(Colors.Red);
                MessageBox.Show(button.Name);
            }
        }

将Button按钮本身当做参数传递
6-2、所以一般绑定自身的时候,例如写个正方形,可以将Width和Height绑定相等

 <StackPanel >
                <Button Background="AliceBlue" Width="200" Height="30" Command="{Binding OpenCommand}" 
                        CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=Width}"/>
            </StackPanel>

我这种写法就是在绑定参数的时候,将宽度当做参数传递过去
十八、给自己看到绑定写法

  <Border Grid.Row="1" BorderThickness="1,1,0,0">
      <Border.BorderBrush>
          <SolidColorBrush Opacity="0.2" Color="Gray" />
      </Border.BorderBrush>
      <Expander
          HorizontalContentAlignment="Stretch"
          Panel.ZIndex="1"
          Background="{x:Null}"
          ExpandDirection="Down"
          IsExpanded="True">
          <Expander.Header>
              <StackPanel Orientation="Horizontal">
                  <TextBlock
                      Grid.Column="1"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      Panel.ZIndex="1"
                      FontFamily="../Assets/Fonts/#iconfont"
                      FontSize="15"
                      Foreground="White"
                      Text="创建的歌单" />
                  <TextBlock
                      Margin="10,0,0,0"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      Panel.ZIndex="10"
                      FontFamily="../Assets/Fonts/#iconfont"
                      FontSize="20"
                      Foreground="White"
                      Text="&#xe695;">
                      <TextBlock.InputBindings>
                          <MouseBinding Command="{Binding CreatePlayListCommand}" MouseAction="LeftClick" />
                      </TextBlock.InputBindings>
                  </TextBlock>
              </StackPanel>
          </Expander.Header>
          <Expander.Content>
              <ItemsControl ItemsSource="{Binding AsedeCreateplayListDtos, Mode=TwoWay}">
                  <ItemsControl.ItemTemplate>
                      <DataTemplate>
                          <Button
                              x:Name="btn"
                              Height="50"
                              Command="{Binding DataContext.OpenPlayListCommand, RelativeSource={RelativeSource AncestorType=Expander}}"
                              CommandParameter="{Binding Id,ConverterParameter=StringToLongConverter}"
                              Content="{Binding PlayListName}"
                              Foreground="White"
                              Style="{StaticResource MaterialDesignFlatButton}"
                              TextBlock.TextAlignment="Center">
                              <!--  使用定位器重新实例化一个Button的数据上下文内容  -->
                              <Button.ContextMenu>
                                  <ContextMenu Background="{x:Null}" Foreground="White">

                                      <ContextMenu.Resources>
                                          
                                          <ObjectDataProvider x:Key="playListDataProvider" ObjectType="{x:Type sign:OperatePlayLists}">
                                              <!--  `技术有限,由于接口不能直接绑定为参数  -->
                                              <!--<ioc:IContainerProvider/>-->
                                          </ObjectDataProvider>
                                      </ContextMenu.Resources>
                                      <ContextMenu.DataContext>
                                          <!--<sign:OperatePlayLists />-->
                                          <Binding Source="{StaticResource playListDataProvider}" />
                                      </ContextMenu.DataContext>

                                      <MenuItem
                                          Background="Gray"
                                          Command="{Binding ReNamePlayListItemCommand}"
                                          CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.Content}"
                                          Header="重命名" />
                                      <MenuItem
                                          Background="Gray"
                                          Command="{Binding DeletePlayListItemCommand}"
                                          CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.CommandParameter}"
                                          Header="删除" />

                                  </ContextMenu>
                              </Button.ContextMenu>
                          </Button>
                          <!--  Style="{StaticResource MaterialDesignFlatDarkBgButton}"  -->
                      </DataTemplate>
                  </ItemsControl.ItemTemplate>
              </ItemsControl>
          </Expander.Content>
      </Expander>
  </Border>

本文作者:孤沉

本文链接:https://www.cnblogs.com/guchen33/p/18094419

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   孤沉  阅读(65)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开