更改所有datagrid行中的图像 [英] change image in all datagrid rows

查看:65
本文介绍了更改所有datagrid行中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据网格,每行都有一个ImageButton.单击ImageButton时,详细信息行将展开/折叠,并且图像会更改(图像为+/-).还有一个选项卡控件,带有用于全部展开(数据网格中的行)和按钮的按钮. 全部折叠(数据网格中的行).当用户单击选项卡控件中的全部展开按钮时,我需要将所有行中的图像都更改为-图像.与全部折叠相同.我是WPF的新手,正在接手一个现有项目, 因此大多数代码对我来说都不为人所知.下面是精简版.

I have a data grid with an ImageButton in every row.  When the ImageButton is clicked, the detail row will expand/collapse and the image changes (images are +/-).  There is also a tab control with buttons for Expand All (rows in the datagrid) and Collapse All (rows in the data grid).  When the user clicks the Expand All button in the tab control I need to change the image in all the rows to the - image.  Same with the Collapse All.  I'm new to WPF and am taking over an existing project, so most of the code is unfamiliar to me.  Below is the stripped down version.

我尝试使用rowdetailvisiblitychanged事件,但无法正常工作.从我对WPF的了解中,我不确定这是否是正确的方法.您能给我的任何帮助将不胜感激.

I tried using the rowdetailvisiblitychanged event, but couldn't get it to work.  From the little I know of WPF, I'm not sure that's the way to go anyway.  Any help you can give me would be greatly appreaciated.

ImageButton类:

ImageButton class:

class ImageButton : Button
{
     public ImageSource Source
     {
        get { return base.GetValue(SourceProperty) as ImageSource; }
        set { base.SetValue(SourceProperty, value); }
     }
     public static readonly DependencyProperty SourceProperty =
          DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton));

    }
}

主窗口XAML:

<Window x:Class="Testing.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local="clr-namespace:Testing"
    xmlns:kimctrl="clr-namespace:Testing.Controls"
    Title="KimsTest" mc:Ignorable="d"
	d:DesignWidth="600"
    WindowStartupLocation="CenterScreen" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TabControl x:Name="tabControlMain" IsSynchronizedWithCurrentItem="True" Grid.Row="0">
                <TabItem x:Name="tabK" Header="Test Stuff" Width="100">
            <DockPanel Height="Auto">
                <ToolBar VerticalAlignment="Top" DockPanel.Dock="Top">

                    <ToggleButton x:Name="btn_ExpandAll" VerticalAlignment="Center" Margin="0" HorizontalAlignment="Stretch" Height="25" IsChecked="False" Click="btnExpandAll_Click">
                        <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="5,0,0,0" HorizontalAlignment="Center">
                            <Image x:Name="btnExpandAll_image" Margin="0,0,5,0" Source="images/expand_all.png" Width="15" Height="15" />
                            <TextBlock x:Name="btnExpandAll_text" TextWrapping="Wrap" d:LayoutOverrides="Width" Margin="0" Text="Expand All" HorizontalAlignment="Left" />
                        </StackPanel>
                    </ToggleButton>
                    <ToggleButton x:Name="btn_CollapseAll" VerticalAlignment="Center" Margin="0" HorizontalAlignment="Stretch" Height="25" IsChecked="False" Click="btnExpandAll_Click">
                        <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="5,0,0,0" HorizontalAlignment="Center">
                            <Image x:Name="btnCollapseAll_image" Margin="0,0,5,0" Source="images/collapse_all.png" Width="15" Height="15" />
                            <TextBlock x:Name="btnCollapseAll_text" TextWrapping="Wrap" d:LayoutOverrides="Width" Margin="0" Text="Collapse All" HorizontalAlignment="Left" />
                        </StackPanel>
                    </ToggleButton>
                </ToolBar>
            </DockPanel>
        </TabItem>
            </TabControl>
        <StackPanel  Grid.Row="1">
        <DataGrid x:Name="dgTest"
                    			ItemsSource="{Binding .}" RowHeaderWidth="0"
                    			AutoGenerateColumns="False" SelectionMode="Single" 
                    			CanUserResizeColumns="True" CanUserResizeRows="False"
                    			VerticalScrollBarVisibility="Auto"
                    			AreRowDetailsFrozen="True" HeadersVisibility="Column"
                    			RowDetailsVisibilityMode="VisibleWhenSelected">

             <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <ListBox Margin="30, 10, 0, 10" >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" Margin="0,0,0,3">
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="Date: " FontWeight="Bold" />
                                        <TextBlock Text="12/1/2011" Margin="0,0,10,0" />
                                        <TextBlock Text="By: " FontWeight="Bold" />
                                        <TextBlock Text="Ktz" Margin="0,0,10,0"/>
                                        <TextBlock Text="Status: " FontWeight="Bold" />
                                        <TextBlock Text="New" Margin="0,0,10,0"/>
                                        
                                    </StackPanel>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="Comments: " FontWeight="Bold" />
                                        <TextBlock Text="Here is my row detail" />
                                    </StackPanel>
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>

            <DataGrid.Columns>
                <DataGridTemplateColumn x:Name="dgcEXPAND_DETAILS">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <kimctrl:ImageButton x:Name="btnExpand" Source="/Testing;component/Images/add.png" Content="Expand Details" 
									                Style="{DynamicResource DataGridButtonStyle}" Click="btnExpand_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

            <DataGridTextColumn x:Name="col1" Header="First Name" Binding="{Binding FName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="False" />
                    <DataGridTextColumn x:Name="col2" Header="Last Name" Binding="{Binding LName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="False" />
            <DataGridTextColumn x:Name="col3" Header="Patient" Binding="{Binding Minor, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="False" />
            </DataGrid.Columns>
        </DataGrid>
        </StackPanel>
    </Grid>
</Window>

mainWindow后面的代码:

mainWindow code behind:

   public partial class MainWindow : Window
    {
            
        public MainWindow()
        {
            InitializeComponent();
            ObservableCollection<Person> patient = new ObservableCollection<Person>();
            Person p = new Person("Collie", "Andrews", "N");
            patient.Add(p);

            p = new Person("Jasmine", "Browe", "Y");
            patient.Add(p);

            dgTest.ItemsSource = patient;
        }

        private void btnExpand_Click(object sender, RoutedEventArgs e)
        {
            DependencyObject obj = (DependencyObject)e.OriginalSource;
            while (!(obj is DataGridRow) && obj != null)
                obj = VisualTreeHelper.GetParent(obj);

            if (obj is DataGridRow)
            {
                if ((obj as DataGridRow).DetailsVisibility == System.Windows.Visibility.Visible)
                {
                    (obj as DataGridRow).DetailsVisibility = Visibility.Collapsed;
                    (sender as Testing.Controls.ImageButton).Content = "Expand Details";
                    (sender as Testing.Controls.ImageButton).Source = new BitmapImage(new Uri(@"/Testing;component/images/add.png", UriKind.Relative));
                }
                else
                {
                    (obj as DataGridRow).DetailsVisibility = Visibility.Visible;
                    (sender as Testing.Controls.ImageButton).Content = "Collapse Details";
                    (sender as Testing.Controls.ImageButton).Source = new BitmapImage(new Uri(@"/Testing;component/images/minus.png", UriKind.Relative));
                }

            }
        }
               
        
        private void btnExpandAll_Click(object sender, RoutedEventArgs e)
        {
            ToggleButton srcButton = e.Source as ToggleButton;
            if (srcButton.Name == "btn_CollapseAll")
                dgTest.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
            
            else
                dgTest.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.Visible;
                       
        }
            
    }

}

样式:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"                   	
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
	                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                    xmlns:kimctrl="clr-namespace:Testing.Controls"
                    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
                    mc:Ignorable="d">

    <Style x:Key="DataGridButtonStyle" TargetType="{x:Type kimctrl:ImageButton}">
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Width" Value="20" />
        <Setter Property="Height" Value="20" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type kimctrl:ImageButton}">
                    <Image x:Name="image" HorizontalAlignment="Center" VerticalAlignment="Center" ClipToBounds="False" Margin="0,0,0,0"
                			Source="{TemplateBinding Source}" ToolTip="{TemplateBinding Content}" Stretch="Fill"/>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="image" Value="0.350"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style TargetType="{x:Type kimctrl:ImageButton}">
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Width" Value="100" />
        <Setter Property="Height" Value="25" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type kimctrl:ImageButton}">
                    <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" 
					Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" 
					RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding IsDefaulted}" 
					SnapsToDevicePixels="true" VerticalAlignment="Center">
                        <StackPanel x:Name="stackPanel" Cursor="Hand" Margin="0" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                            <Image x:Name="image" HorizontalAlignment="Center" VerticalAlignment="Center" Width="20" Height="20" ClipToBounds="False" Margin="0,0,5,0"
                			Source="{TemplateBinding Source}" Stretch="Fill"/>
                            <ContentPresenter VerticalAlignment="Center" />
                        </StackPanel>
                    </Microsoft_Windows_Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="ToggleButton.IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                            <Setter Property="Opacity" TargetName="image" Value="0.350"/>
                        </Trigger>
                    </ControlTemplate.Triggers>


                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

推荐答案

此代码告诉我们,有一个ImageButton的属性名为Source.如果要更改图像的按钮绑定到此属性,那么您要做的就是更改Source属性本身,如下所示:

MyImageButton.Source = myImageSource ...

MyImageButton.Source = myImageSource...

class ImageButton : 按钮
{
   
公共 ImageSource
   
{
      
获取 { 返回 基本 . GetValue ( SourceProperty ) as ImageSource ; }
      
设置 { base . SetValue ( SourceProperty ); }
   
}
   
公共 静态 只读 DependencyProperty SourceProperty =
        
DependencyProperty . 注册 ( 源" typeof ( ImageSource ), typeof ( ImageButton )));

   
}
}

class ImageButton : Button
{
    
public ImageSource Source
    
{
       
get { return base.GetValue(SourceProperty) as ImageSource; }
       
set { base.SetValue(SourceProperty, value); }
    
}
    
public static readonly DependencyProperty SourceProperty =
         
DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton));

   
}
}

但是等等,我不想更改每个ImageButton ...在设置模板的MainControl中将其绑定到将在< UserControl.Resouces>中设置的Dynamic Resouces.区域.

But wait I don't want to change every single ImageButton... Ok in the MainControl that set's up the template bind it to a Dynamic Resouces which would be set in the <UserControl.Resouces> area.. 

所以它像IMAGEBUTTON一样工作.Souce是DataTemplate的一部分,因为它是具有依赖项属性和CLR包装器的子控件,您可以使用它将此值设置为UserControl中的资源图像.然后,您只需要更改 代码隐藏的简单资源...

So it works like this IMAGEBUTTON.Souce is in a part of DataTemplate, because it is a sub control with a dependency property and CLR wrapper, you can set this value to the resource image in the Usercontrol using it.  You then only need to change that resource which is simple in code-behind...

var something =(ImageSource)This.FindResouce("TheImageSourceKey");

var thing =(ImageSource) This.FindResouce("TheImageSourceKey");

thing.ImageSource = NewImage.Source;

thing.ImageSource = NewImage.Source;


这篇关于更改所有datagrid行中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆