Showing posts with label wpf. Show all posts
Showing posts with label wpf. Show all posts

Friday, August 3, 2012

Make GridColumns align in two different Grids in WPF XAML

In XAML UI, some times we want to make GridColumn Width synchronized with other GridColumns in other Grids.

WPF provided a property called  SharedSizeGroup  which allows sizing properties shared between ColumnDefinition or RowDefinition.

And remeber to set  Grid.IsSharedSizeScope="True".


However , when we want one column take up all the available space, like the example above. You will find out that even you write Width="*" still doesn't work as SharedSizeGroup will make it as short as possible.

My solution is , Shared all the columns size except the one contain TextBox.


            <Grid  Grid.IsSharedSizeScope="True">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                </Grid.RowDefinitions>
                <Grid Name="Grid1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto" SharedSizeGroup="a" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="auto" SharedSizeGroup="c"/>
                        <ColumnDefinition Width="auto"  SharedSizeGroup="d"/>
                    </Grid.ColumnDefinitions>
                 ....
                </Grid>
                <Grid Name="Grid2">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto" SharedSizeGroup="a" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="auto" SharedSizeGroup="c"/>
                        <ColumnDefinition Width="auto"  SharedSizeGroup="d"/>
                    </Grid.ColumnDefinitions>
                 .........
                </Grid>

Thursday, August 2, 2012

WPF XAML GridSplitter Style


<Style x:Key="gridSplitterStyle" TargetType="{x:Type GridSplitter}">
    <Setter Property="FrameworkElement.Height" Value="6"/>
    <Setter Property="TextElement.Foreground" Value="#FF204D89" />
    <Setter Property="Border.BorderThickness" Value="0,0,0,0" />
    <Setter Property="UIElement.SnapsToDevicePixels" Value="True" />
    <Setter Property="UIElement.Focusable" Value="False" />
    <Setter Property="FrameworkElement.Cursor" Value="SizeNS" />
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                    <Border BorderThickness="0,0,0,0" >
                        <Canvas Width="19" Height="3">
                            <Rectangle Fill="{TemplateBinding TextElement.Foreground}" Width="2" Height="2" Canvas.Left="0" Canvas.Top="0" />
                            <Rectangle Fill="{TemplateBinding TextElement.Foreground}" Width="2" Height="2" Canvas.Left="4" Canvas.Top="0" />
                            <Rectangle Fill="{TemplateBinding TextElement.Foreground}" Width="2" Height="2" Canvas.Left="8" Canvas.Top="0" />
                            <Rectangle Fill="{TemplateBinding TextElement.Foreground}" Width="2" Height="2" Canvas.Left="12" Canvas.Top="0" />
                            <Rectangle Fill="{TemplateBinding TextElement.Foreground}" Width="2" Height="2" Canvas.Left="16" Canvas.Top="0" />
                        </Canvas>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Tuesday, September 20, 2011

Finding an ancestor and children of a WPF dependency object

Below are from : http://www.hardcodet.net/2008/02/find-wpf-parent


This is a simple snippet which helps you to find a specified parent of a given WPF dependency object somewhere in its visual tree:
(Snippet updated 2009.09.14)

/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(this DependencyObject child)
    where T : DependencyObject
{

Thursday, August 25, 2011

C# Invoke particular EventHandler in InvocationList

I am trying to get particular EventHandler get fired.

Event ProjectChanged was hooked by several EventHandlers


public static event EventHandler ProjectChanged;


foreach (var eventHandler in ProjectChanged.GetInvocationList())
{
    if (eventHandler.Method.Name == "UserContext_ProjectChanged")
    {
        eventHandler.DynamicInvoke(null,null);
    }
}

Wednesday, August 17, 2011

WPF GridViewColumn Width 100 percent

<local:ListViewEx.View>
    <GridView ColumnHeaderContainerStyle="{StaticResource CustomHeaderStyle}">
        <GridViewColumn Header="xxx" 
             Width="{Binding RelativeSource={RelativeSource FindAncestor, 
             AncestorType=ListView}, Path=ActualWidth}">
             <GridViewColumn.CellTemplate>

Monday, June 27, 2011

Icon Render WPF

RenderOptions.BitmapScalingMode="NearestNeighbor"                            RenderOptions.EdgeMode="Aliased"

Sunday, June 26, 2011

Text Trimming and ToolTip bind to itself

TextTrimming="CharacterEllipsis" TextWrapping="Wrap" ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}

Friday, May 27, 2011

Cool stuff in .NET 4.0: System.Threading.Tasks.TaskScheduler

private void Save()
{
    System.Threading.Tasks.TaskScheduler uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
    System.Threading.Tasks.Task<ErrorEnum>.Factory.StartNew(() =>
    {
        ErrorEnum callResult = ErrorEnum.OK;
        try
        {
            IsIdle = false;
            callResult = (ErrorEnum)DataContext.DomainRepository.SaveDomain(_domain);
            if (callResult != ErrorEnum.OK)
            {
                // If remote saving fails, rollback all the changes
                Rollback();
            }
            else
            {
                // If remote saving succeeds, save changes to local db
                SaveChangesToLocalDB();
            }
            return callResult;
        }
        catch (Exception ex)
        {
            LogManager.AddCMEventLog("DomainSettingsViewModel.Save", ex);
            // If anything goes wrong, rollback all the changes
            return ErrorEnum.LocalFatalAnonymousError;
        }
        finally
        {
            IsIdle = true;
        }
    }).ContinueWith(task => ShowResult(task.Result), uiScheduler);
}




This running tasks in background thread, then call UI thread to execute the ShowResult() function, Just like UIDispatcher

Thursday, April 14, 2011

Set Window on top of others

The correct way to implement a modal window is by setting  this.Owner = Application.Current.MainWindow; in the XAML, and show the dialog by using DialogName.ShowDialog();

Sunday, March 27, 2011

TextTrimming ToolTip in WPF

<TextBlock Text="{Binding State}" TextTrimming="CharacterEllipsis" Foreground="#6D6D6D"
                                                           ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}"/>

Tuesday, March 8, 2011

ListView ObservableCollection Selection

I have ListView with GridView inside (in order to divide ListView for some columns). I bind ObservableCollection of some objects with that ListView.DataContext when main UserControl is loaded. Items show up but when i create two objects which fields have same values (and put them to observable collection), that new items show up in ListView. Problem is that, when user clicks and select one of the new item - both select.

When value of one of mentioned objects changes (and is different) problem doesn't exist, ListView treat them as it should.

Wednesday, February 23, 2011

C# Write Access Check

        /// <summary> Checks for write access for the given file.
        /// </summary>
        /// <param name="fileName">The filename.</param>
        /// <returns>true, if write access is allowed, otherwise false</returns>
        public static bool WriteAccess(string dire)
        {

            // Get the access rules of the specified files (user groups and user names that have access to the file)
            var rules = Directory.GetAccessControl(dire).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            // Get the identity of the current user and the groups that the user is in.
            var groups = WindowsIdentity.GetCurrent().Groups;
            string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;

            // Check if writing to the file is explicitly denied for this user or a group the user is in.
            if (rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Deny && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData))
                return false;

            // Check if writing is allowed
            return rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Allow && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData);
        }

WPF Mouse Cursors busy

Mouse.OverrideCursor = Cursors.Wait;
Mouse.OverrideCursor = null;

Wednesday, February 9, 2011

Articles to read about Threads

http://msdn.microsoft.com/en-us/magazine/cc163328.aspx

http://msdn.microsoft.com/en-us/library/ms741870.aspx

c# thread

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
    {
        ChangeCMFolderLocationEventHandler(sender, oea);
    }));



Dispatcher.Invoke(new Action(() => mainDockingPane.mainDockingManager.ExecuteClose(mainDockingPane.Detail)));

Saturday, January 29, 2011

Marking Routed Events as Handled, and Class Handling

Marking Routed Events as Handled, and Class Handling: "Also, input routed events that have a tunneling and bubbling pair have a distinct handling logic. If the tunneling/preview routed event is marked as handled by an event listener, then the bubbling routed event will be marked handled even before any listeners of the bubbling routed event receive it. The tunneling and bubbling routed events are technically separate events, but they deliberately share the same instance of event data to enable this behavior."

Thursday, January 13, 2011

Use the "using" C# key word to build sql connection

While reviewing some C# code written by a newbie programmer and buddy of mine, I noticed a lack of calling Dispose() on SqlConnection and SqlCommand objects. And in all cases, the database code was not placed in try / finally blocks. This is typical newbie style of development that everyone, including myself, attempted in the very beginning.

SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cm = new SqlCommand(commandString, cn);

Thursday, December 30, 2010

Set "Auto" to GridView Colum Width when re-binding data to the GridView

The GridView Colum Width is a headache.

detailView.Columns.OfType<System.Windows.Controls.GridViewColumn>().ToList().ForEach(c => c.Width = c.ActualWidth);
detailView.Columns.OfType<System.Windows.Controls.GridViewColumn>().ToList().ForEach(c => c.Width = Double.NaN);


http://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn.width.aspx
Double.NaN means auto-size