lundi 29 juin 2015

WPF- Bind tab selected/unselected event to method in tab viewmodel

I've got a ViewModel that holds a List of ViewModels that will be open as tabs by the view, and I want methods within the tab viewmodels to run when a tab gets selected/unselected. Currently I've got the TabControl in the view set up liek this:

<Window.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type VM1}">
            <View1 />
        </DataTemplate>
        <DataTemplate DataType="{x:Type VM2}">
            <View2 />
        </DataTemplate>
        <DataTemplate DataType="{x:Type VM3}">
            <View3 />
        </DataTemplate>

        <DataTemplate x:Key="TabItemTemplate">
            <Grid Width="Auto" Height="Auto">
                <ContentPresenter ContentSource="Header" Margin="3" 
                        Content="{Binding NiceName}"
                        HorizontalAlignment="Center" VerticalAlignment="Center">
                </ContentPresenter>
            </Grid>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>

<TabControl Grid.IsSharedSizeScope="True" 
                SelectedIndex="{Binding CurrentTab, Mode=TwoWay}" 
                ItemsSource="{Binding Tabs}" 
                ItemTemplate="{StaticResource TabItemTemplate}" />

This all works fine, but I can't figure how to bind a tab change event to a methos within the tabbed viewmodels. You can change TabControl.SelectionChanged, but this would force the tabcontrol holding ViewModel to know what to call on it's tabs, forcing them to implement a specific interface. Is there any way to avoid this coupling in the tab holder ViewModel?

Multiple Inheritance - want to extend a class that extends Panel, but I also want to extend StackPanel

I have a control, ShrinkingTabPanel, that proportionally resizes tabs as they're added so they all fit (like Chrome). However, it extends Panel, and this doesn't work with the functionality I'm trying to achieve - the width of the ShrinkingTabPanel doesn't increase with number of items like it should.

When I changed the class to extend StackPanel instead, that was the exact functionality I needed.

However, ShrinkingTabPanel is a control that is part of a library that we bought, and it's usually discouraged to change imported source code.

I know multiple inheritance isn't allowed in C#, but is there any way I can "effectively" extend ShrinkingTabPanel and StackPanel in one class?

The first solution I thought of was to make a new class that extended StackPanel, and to just call ShrinkingTabPanel.ArrangeOverride() and ShrinkingTabPanel.MeasureOverride() within the respective methods, effectively extending ShrinkingTabPanel. But I'm not sure if that's the smartest idea.

Check ComboBox (Xceed WPF Toolkit), How to get short name to display from database?

This is my first post and I am a relative newbie regarding all things programming related. I hope you will be patient with me. I have a WPF application I am working on. My current issue is a Check ComboBox I am using. When I make selections out of the list that is pulled from a sqlite database file, the full name of the selection is displayed. I would like to change this and have a short name from the database appear in the ComboBox area while leaving the long descriptive name in the dropdown portion. I thought working with display and value member would help out, but have yet to get it working. I can get one or the other by changing the column index reference to my sqlite db. The ComboBox is a multi-select item and it needs to update as selections are made or cleared. Below is the bit of code I have that populates the ComboBox. I am unable to attach an image of the data due to low Rep numbers. Column 0 is the full descriptive name, Column 1 has the short name I am interested in displaying.

public void Fill_Modality()

        {
            SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
            try
            {
                sqliteCon.Open();
                string Query = "Select * from Modality_list";

                SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
                SQLiteDataReader dr = createCommand.ExecuteReader();
                while (dr.Read())
                {
                    string modname = dr.GetString(0);
                    Modality_Select.Items.Add(modname);
                }

                dr.Close();
                sqliteCon.Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);

            }
        }

Thank you for any help you may be able to provide.

Patrick

WPF (Vb.net): How to change the application icon dynamically?

I'm working on a simple application for Windows (if you ask, Windows Vista+ compatible) and I'd like the user to be able to change the icon of the application.

I have two icons, one old and one new, and I'd like the user to be able to go to Settings (for example) and check "Use old icon" or uncheck it, and depending on the chosen option the icon of the application - the shortcut desktop icon, the icon in the tray bar, the icon in the ALT+TAB menu, and so on - will change to the one chosen.

The application can make the change after it has been reopened (it's not important to show it immediatelly).

Is this possible? Or the only way is to set the icon through the project settings before compiling it?

Thanks for your help and time!

Multiple values selection in a desktop application

I was preparing a MS Access based Desktop Database Application for a Coaching classes. Now since previously the application only consisted of the basic form based functions including, adding new student, displaying the list of students, the fee structure and the attendance. Now he's asked me to prepare a more dynamic application, adding following functionalities along with the previous, 1. A question based contents, which can be selected at one time

eg: q1
 q2
 q3
 q4

So if we select q1 & q4, only those two questions should be displaying in the next sheet(wordsheet preferably).
Thus helping him to make a quick question paper.

I am not much familiar on how to achieve this on Ms Access. I tried Macros, but I couldn't find one which selects multiple questions and achieves the above task.
So i wanted to get an help on this, is there a way to achieve this on MS Access or is there some other technology which might help me on this?

WPF How to make a Viewbox aware of its available space from within a StackPanel

I have a custom WPF control based on Soroosh Davaee’s ImageButton example at http://ift.tt/T2BK1s. The custom control combines an Image and TextBlock in a horizontal StackPanel within a Button. (BTW, to get Soroosh’s example to run, I had to edit the solution properties so that “SampleView” is the startup project rather than “ExtendedButton” being the startup project.)

I want the text in the TextBlock to automatically shrink if necessary to avoid clipping at the right edge if the text is too long to fit naturally in the button. For example, if I edit Soroosh's MainWindow.xaml to make the button text too long to fit...

    ...
    <EB:ImageButton Width="100" Height="30" Content="TextTooLongToFitInTheButton" Grid.Row="2"
    ...
    <EB:ImageButton Width="100" Height="30" Content="TextTooLongToFitInTheButton" Grid.Row="2"
    ...

...the result is the following buttons with clipped text:

Buttons with clipped text

In researching this, it seems the simplest way to auto-shrink the content of a TextBlock is to wrap it within a Viewbox:

<Viewbox StretchDirection="DownOnly" Stretch="Fill">
    <TextBlock ... />
</Viewbox>

DownOnly apparently prevents the Viewbox from enlarging the text to fill the space, and Fill (as opposed to Uniform) seems to tell it to stretch (shrink) only the dimension that needs to shrink (i.e. the horizontal dimension in my case).

In Soroosh's example Generic.xaml file, I wrapped the TextBlock in such a Viewbox:

     <Button >
         <StackPanel Orientation="Horizontal">
             <Image Margin="2 0"
                    Source="{TemplateBinding Image}"
                    Width="{TemplateBinding ImageWidth}"
                    Height="{TemplateBinding ImageHeight}"
                    Visibility="{TemplateBinding Image,Converter={StaticResource VisibilityConvertor}}"
                    VerticalAlignment="Center"/>
I added-->   <Viewbox StretchDirection="DownOnly" Stretch="Fill">
             <TextBlock Text="{TemplateBinding Content}"
                    VerticalAlignment="Center"/>
I added-->   </Viewbox>
         </StackPanel>
     </Button>

This produced exactly the same clipped button text. Just experimenting, I tried forcing the Viewbox to have a fixed width...

             <Viewbox StretchDirection="DownOnly" Stretch="Fill" Width="60">

...which produced this:

Viewbox with manually-sized width

...which shows the capability of the Viewbox, if only it could somehow know its available width when it's inside the StackPanel.

I did note that if I wrap the Viewbox around the whole StackPanel, it successfully auto-shrinks the entire content of the StackPanel:

     <Button >
         <Viewbox StretchDirection="DownOnly" Stretch="Fill" Width="60">
             <StackPanel Orientation="Horizontal">
                 <Image Margin="2 0"
                    Source="{TemplateBinding Image}"
                    Width="{TemplateBinding ImageWidth}"
                    Height="{TemplateBinding ImageHeight}"
                    Visibility="{TemplateBinding Image,Converter={StaticResource VisibilityConvertor}}"
                    VerticalAlignment="Center"/>
                 <TextBlock Text="{TemplateBinding Content}"
                    VerticalAlignment="Center"/>
             </StackPanel>
         </Viewbox>
     </Button>

...which produces very nearly what I want:

Viewbox wrapping the entire StackPanel

...but both the image and text are shrunk, and I want only the text shrunk.

How can I make the Viewbox, wrapping only the TextBox, know its available width (and height, I suppose) from within a cell of the StackPanel?

WPF media kit camera orientation not working properly

I am developing a camera application for tablet PC running Windows 8.1 using wpf mediakit. I am using VideoCapture for this,

<Controls:VideoCaptureElement 
                    FPS="30"
                    x:Name="videoElement" Stretch="UniformToFill" 
                    HorizontalAlignment="Center"

                    VerticalAlignment="Center"
                    Height="Auto"
                    Width="Auto"
                    Margin="0, 0, 0, 0"
                    EnableSampleGrabbing="True"
                    Visibility="Visible"
                    UseYuv="False"
                    UseStillPin="False"
                    UnloadedBehavior="Close" >
                    <Controls:VideoCaptureElement.LayoutTransform>
                        <RotateTransform Angle="0" />
                    </Controls:VideoCaptureElement.LayoutTransform>
                </Controls:VideoCaptureElement>

The problem is that, when I change the orientation, the camera is not changing accordingly.

ie, If I am in a portrait view, the camera preview will be flipped.

How can I rotate the preview whenever the user changes the orientation ?

Tab Control without a line when selected

I want to show Tab control in WPF without using a line. My code as follows:-

            <TabItem Header="Tab 0">
            <TabItem.Style>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border  Name="Border" Margin="0,0,0,0" BorderBrush="Gray">
                                        <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Center" ContentSource="Header" Margin="12,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                </Grid>
                                <ControlTemplate.Triggers>

                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="Panel.ZIndex" Value="100" />
                                        <Setter TargetName="Border" Property="Background" Value="White" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>

                                    <Trigger Property="IsSelected" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#DDDDDD" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter TargetName="Border" Property="Background" Value="White" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>

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

            <Grid Background="White" />
        </TabItem>

When I don't use style <TabItem.Style> Tab is coming without Line as per my requirement, but I need to use <TabItem.Style> because of the requirement.

Please help.

Thanks

Show Notification in Wpf

I want to show a grid that involve a label and I want to show this in left-above of another grid.the wpf code(xml) is this :

<Grid.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" >
                            <SplineDoubleKeyFrame KeyTime="0:0:0" Value="0"/>
                            <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="1"/>
                        </DoubleAnimationUsingKeyFrames>
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                            <SplineDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
                            <SplineDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
                        </DoubleAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Grid.Triggers>
        <Grid.RenderTransform>
        <ScaleTransform ScaleY="1" />

</Grid>

How to create this notification when press a button? I have the C# code for this. thanks.

WPF Drag an email item from desktop

I am trying to drag an email into wpf canvas but not getting any solution. I can able to do drag and drop an email with attachments using Outlook data object by FileDescriptorW format.

My application color look with lines when

Please see this screenshot:

enter image description here

As you can see there is several 'lines' around my application Background, this when i connect to the machine that running my application using Remote Desktop or Radmin.

This is when i am running my application on my local machine:

enter image description here

Any suggestions how to avoid this behavior ?

Validating POCO / VM class

I have an MVVM project which is hooked up to EF6 (Database First). I would like to use Data Annotations to take care of the validation, do I need to create a public properties on the VM to represent each field in the POCO class or do I add it to the POCO class directly (when the database is updated I will surely have to go through the process again or is there a way of separating this additional validation?)

ListView Binding from List

I search over all internet but I didnt find an answer. I am new in MVVM and also pretty new in WPF :) So sorry for my lack of knowledge

I have defined method in one class where I search for USB devices (with help of another .dll library):

public void FindDevices()
    {
        _deviceList = HidDevices.Enumerate(VendorID, ProductID).ToArray();

        String[] deviceSNstring = new String[_deviceList.Length];
        String[] deviceManufacturerstring = new String[_deviceList.Length];
        String[] deviceProductstring = new String[_deviceList.Length];

        List<Devices> devices = new List<Devices>();

An later I become a nice List of devices.

In another class I want to bind this List in ViewModel class into ListView. How to do it? And I must Also start method to find my devices "FindDevices" :)

Command doesn't work on top level MenuItem in MVVM

It works fine if the MenuItem doesn't have a sub MenuItem, like this:

<MenuItem Header = "Open" Command="{Binding OpenCommand}"/>

but, when I add a sub MenuItem to it, the Command doesn't work:

<MenuItem Header = "Open" Command="{Binding OpenCommand}">
    <MenuItem />
</MenuItem>

I know I can add the Command to the header as a remedy:

<MenuItem>
    <MenuItem.Header>
        <Button Content = "Open" Command="{Binding OpenCommand}"/>
    </MenuItem.Header>
    <MenuItem/>
</MenuItem>

but is there a elegant way to fix it? any help will be appreciate.

WPF DataGrid Row Background Color depending of Last Cell of the Row

So for the better understanding. I have 2 SQL DataTables (server and client) and put them together into one DataGrid. Before i put the DataTables into the DataGrid, i added a column with a number, so that i can later see from which DataTable the row comes from. Now i wanted to change the background of the row depending of which DataTable it comes from.

My plan was:

-Use the number of the column i added at the end of the row to decide which color to use for the row.

But my problem:

  • How can i get the Data of the last cell of the row in wpf?
  • Can i just delete the Column after finishing this process?
  • And will the Color stay, even after sorting the rows afterwards?

Sorry, but i just cant get the Data of the specific cells....

Is there maybe a better way to do all of this?

Thank you for your Help!!!!

MUI: Modify appearance of back button

How can I easily override the styling of the back button. It's currently buried in ModernWindow.xaml, and I'd prefer not to compile in all of MUI into my solution.

<!-- back button -->
<controls:ModernButton Margin="8,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"
                       EllipseDiameter="24" IconWidth="12" IconHeight="12"
                       IconData="F1 M 33,22L 33,26L 19.75,26L 27,33L 20.5,33L 11,24L 20.5,15L 27,15L 19.75,22L 33,22 Z"
                       Command="NavigationCommands.BrowseBack"
                       CommandTarget="{Binding ElementName=ContentFrame}" 
                       ToolTip="{x:Static modernui:Resources.Back}"
                       WindowChrome.IsHitTestVisibleInChrome="True" />

I just want to make it a little bigger and give it a background color of the current highlight color (i.e. blue).

I have a request to make it look more like the huge blue back button in Internet Explorer.

enter image description here

When Tooltip.Content gets populated?

I need to use the Tooltip.Content information of any given control.

Lets say there is a a control TextBlock and it is bound to a Tooltip. I access the Tooltip of the TextBlock by var toolTip=(ToolTip)TextBlock.ToolTip. The value of toolTip.Content remains null, but if I do a mouse hover over the control it is populated with the desired value.

How do I get the tooltip to populate its content before triggering a mouse over the control? Does the Tooltip loads its content lazily or is there something I am missing?

Bring MainWindow to front, not always on top, and wait for it to close

I have a WPF application with a single window. When the application starts, I want to bring it to the front. I also want to let the user move other windows on top of it (it shouldn't be always on top), and I want to wait for the window to close in code. Perhaps I am being too picky as WPF does not appear to support this.

Currently, I have this:

MainWindow.Topmost = true;
MainWindow.Show();
MainWindow.Activate();
MainWindow.Topmost = false;
MainWindow.Focus();

It's great except that MainWindow.Show() returns immediately and execution resumes. In the past, we were using

MainWindow.TopMost = true;
MainWindow.ShowDialog();

But then this window is always on top and obstructs all other windows (not the best user experience). Are there any other options? Please feel free to suggest I am architecting this incorrectly as well. Thank you!

Why my UserControl with a template of a Path is not properly clickable?

I created a class derived from UserControl, directly on code (without XAML), and defined a ControlTemplate in a ResourceDictionary. This control template is a pair of ellipses, as follows:

<ControlTemplate x:Key="MusclePositionControlTemplate" TargetType="{x:Type local:MusclePositionControl}">
    <ControlTemplate.Resources>
        <EllipseGeometry x:Key="bolinha" RadiusX="{StaticResource radius}" RadiusY="{StaticResource radius}">
            <EllipseGeometry.Center>
                <Point X="0" Y="{StaticResource distance}"/>
            </EllipseGeometry.Center>
        </EllipseGeometry>                      
    </ControlTemplate.Resources>
        <Path Fill="#9900ffff" StrokeThickness="1" Stroke="Black">
            <Path.Data>
                <GeometryGroup>
                    <StaticResource ResourceKey="bolinha"/>
                    <GeometryGroup>
                        <GeometryGroup.Transform>
                            <ScaleTransform ScaleY="-1"/>
                        </GeometryGroup.Transform>
                        <StaticResource ResourceKey="bolinha"/>
                    </GeometryGroup>
                </GeometryGroup>                                
            </Path.Data>        
            <Path.RenderTransform>
                <TransformGroup>
                    <RotateTransform Angle="{Binding Angle, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
                    <TranslateTransform
                        X="{Binding X, RelativeSource={RelativeSource Mode=TemplatedParent}}"
                        Y="{Binding Y, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
                </TransformGroup>               
            </Path.RenderTransform>
        </Path>
</ControlTemplate>

When I edit this template in Blend, I can select the path clicking on it, and it displays its outlines like this:

enter image description here

But when I add the actual control to a canvas, with its X, Y and Angle properties set to some value, the control renders itself fine, but its defining geometry keeps being that of a rectangle at the origin, and this affects hit testing (I cannot select at design time, or click at runtime, by clicking at the shape itself):

enter image description here

So my questions are:

  1. How should I create a ControlTemplate using a Path as "root" visual element, so that the clickable area of the control is that Path?
  2. Assuming a Path should not or could not be used as root visual for a ControlTemplate, how should I achieve the same end result?

How to create WAV header file for kinect v2.0 audio source?

I collect kinect audio frame in a byte array. how to create wav header file for this byte array that provided by kinect? i see and use http://ift.tt/1GKJnv7 ,but after the file is saved, file has a capacity and duration but audio not recorded.

Dynamic binding?

May be not a right title for the question but I will try to explain: My TextBox already bound to a property like:

class MyViewModel
    public string TextVal
    {
        get
        {
             if (View != null)
                 return View.Model.TextForValueField;   // other satrts
                 return defaultModel.TextForValueField;// first start
             }
        set
        {
             .....//some setters logic with View.Model.TextForValueField
        } 
    }

When program starts the View is not open so getter binds the value of the field to the value in default model and it is correct, but then , when I open new View my getter correctly returns values from corresponding View.Model.TextForValueField but the field of TextBox on my windows ribbon menu shows the initial value from default model (?) Why?? the xaml for binding is :

<Setter Property="Text" Value="{Binding MyViewModel.YIncr, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Perhaps there is a way to call getter once more when a View starts? Something like "Refresh" for ribbons??

HttpUtility.ParseQueryString in partial trust environment

I'm just getting started with writing an XBAP page. I need to pass some information into the XBAP context via query string parameters. I am expecting the XBAP to execute in a partial trust context.

When I run the following XBAP code-behind hosted on IIS, it throws the following

System.Reflection.TargetInvocationException:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.

---> System.Security.SecurityException: That assembly does not allow partially trusted callers. at UI.UIEntryPage..ctor()

If I comment out the call to HttpUtility.ParseQueryString(), the XBAP loads properly, so it seems I'm not allowed to use HttpUtility to parse the query string in a partial trust context? (I find this surprising since a static method to parse a string into a NameValueCollection doesn't really seem like a security risk...)

Is there anything I can do to call this method in a partial trust context? Or, failing that, how can I parse the query string parameters securely without using HttpUtility?

namespace UI
{
    /// <summary>
    /// Interaction logic for UIEntryPage.xaml
    /// </summary>
    public partial class UIEntryPage : Page
    {
        public UIEntryPage()
        {
            InitializeComponent();

            if (!ApplicationDeployment.IsNetworkDeployed) return;

            Uri launchUri = ApplicationDeployment.CurrentDeployment.ActivationUri;

            string query = launchUri.Query;

            // This line causes an exception to be thrown
            // when the XBAP is loaded.
            NameValueCollection uriParameters = HttpUtility.ParseQueryString(query);

            foreach (string key in uriParameters.AllKeys)
            {
                UriParameters.Add(key, uriParameters[key]);
            }

            DataContext = this;
        }

        public readonly Dictionary<string, string> UriParameters = new Dictionary<string, string>();
        }
    }
}

WPF passworChar '<' char is not possible

I was creating a wpf application while adding a passwordbox, I need to display '<' instead of '*'. I wrote the following code but unfortunately it is not working.It is throwing an error

<PasswordBox PasswordChar="<"></PasswordBox>. 

How to bind panels with controls in devexpress docklayoutmanager

I have a document layout manager programmatically getting panels and controls which is having panels and controls in them.

While saving, I am achieving this with SaveLayoutToXml() for my panels and Serializing controls using bformatter.Serialize();.

since i have lot of panels and unique controls in them. I want to get the same controls back in same panels as it was before saving and serializing. Please provide me with a code to identify with a unique id for both panels and controls.

And do I have any integer id to which I can assign GUID as BindableName does not work with it.

Thanks Desh

WPF cannot find resource dictionaries

So the image below says everything. WPF cannot locate some of the xaml files. I have tried moving them around, to no avail. All of them have their Build Action set to Page and Custom Tool set to MSBuild:Compile. Don't know what I'm missing here.

Errors Snapshot

How to get Service Reference Address from WCF Application

I need to add a Service Reference to one of my applications. Now in the Add Service Reference box, there is an Address field. How do I get the Address field or URL from the WCF application to add it in my new application?

I've tried to use the URL: http://localhost:53101/ that I got from the WCF application's properties, but it gives me this error:

There was an error downloading 'http://localhost:53101/_vti_bin/ListData.svc/$metadata'. The request failed with HTTP status 404: Not Found. Metadata contains a reference that cannot be resolved: 'http://localhost:53101/'. The remote server returned an unexpected response: (405) Method Not Allowed. The remote server returned an error: (405) Method Not Allowed. If the service is defined in the current solution, try building the solution and adding the service reference again.

I've also tried to build the WCF solution, then trying to add the reference again, but it gives me the same error.

Add font to my application in order to verify that in the machine that running my app this font will not be missing

in my application in am using specific font and i am notice that in other machines that running my application this font is missing and in this case my application using different font (maybe default one ) so i wonder how to add this specific font to my application.

WPF ButtonStyle with PathGeometry as an icon

How I can add PathGeometry as an Icon to the style of the button/radbutton?

In resources I have for example:

 <PathGeometry x:Key="HomeIconData">F1 M 22,19L 24,19L 24,57L 22,57L 22,19 Z M 26,57L 26,19.0001L 53.9999,19.0001L 53.9999,57L 26,57 Z M 30,24L 30,27L 50,27L 50,24L 30,24 Z M 30,32L 30,35L 33,35L 33,32L 30,32 Z M 36,32L 36,35L 49,35L 49,32L 36,32 Z M 30,40L 30,43L 33,43L 33,40L 30,40 Z M 36,40L 36,43L 48,43L 48,40L 36,40 Z M 30,48L 30,51L 33,51L 33,48L 30,48 Z M 36,48L 36,51L 50,51L 50,48L 36,48 Z</PathGeometry>

With Path I add this to the style:

 <Grid Margin="0,30,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="36" Width="41">
  <Path HorizontalAlignment="Center" Data="{Binding Source={StaticResource path1}, Path=Data}" Fill="#FFFFFFFF" Height="27" Stretch="Fill" Width="28.167" VerticalAlignment="Bottom" />
  </Grid>

How can I do the same with PathGeometry? Thanks

How to create menu with elements only one of which can be checked

What is the shortest way to create menu with elements only one of which can be checked at same time? So if user click second element, first check becomes unchecked. Actually would prefer small circles instead of checks.

   <Menu>
        <MenuItem Header="File">
            <MenuItem Header="Numer">
                <MenuItem Header="1"
                          IsCheckable="True" />
                <MenuItem Header="2"
                          IsCheckable="True" />
            </MenuItem>
        </MenuItem>
    </Menu>

How to remove default close button in RadDesktopAlert control of telerik for wpf, is this possible?

public RadDesktopAlertManager ExecuteBatchDesktopAlert=new RadDesktopAlertManager(AlertScreenPosition.BottomRight,new Point(5,5),5); public void ShowNotification(string header, string content) { var radAlert = new RadDesktopAlert {
Header = header, Content = content, Height = 90, Width = 300, Opacity = 1, Background = Brushes.Gray,

        };
        ExecuteBatchDesktopAlert.ShowAlert(radAlert);            
    }

Animation during User-control change in wpf

I am looking for this:

Say For example, I have 2 user-controls: uc1.xaml and uc2.xaml and 1 mainwindow in my application. Now, when the application opens mainwindow will show 1st usercontrol i.e uc1. Hence, how to animate to slide effect or any other effect while mainwindow shows uc1. Also, when I click button on uc1, mainwindow switch from uc1 to uc2. I also need to have animation at this step. Kindly help me with some sample code.

Kindly help!!

Note: I am using wpf desktop application and it is "NOT" winforms application.

Thank you very much in advance.

Wants to assing value to datagridtextbox control from Another Control and Binding path should Datacolumn name [on hold]

Here i got Id control text in ParentCode but while saving data value could not bind to parentcode column

Stop button event WPF, Selenium

How to stop button event when exception fired..?I used try catch blocks, if exception fired it will try to execute next code, i dont want that...pls check comments in code..M i using try catch blocks wrongly..?

here is my code:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
try
 {
 driver.FindElement(By.CssSelector(".username")).SendKeys("abc");
 driver.FindElement(By.CssSelector(".password")).SendKeys("abcpassword");
 driver.FindElement(By.XPath("//a[2]/img")).Click();
 }
catch(Exception ex)
{
driver.Quit();
MessegeBox.Show("Log in failed");
//stop button event here only if exception fired
}

try
{
new SelectElement(driver.FindElement(By.Id("CId"))).SelectByText("CVB");
driver.FindElement(By.Name("ddd")).Click();
}

catch(Exception ex)
{   
driver.Quit();
MessegeBox.Show("Log in failed");
//stop button event here only if exception fired
}

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
xlApp.DisplayAlerts = false;
object misValue = System.Reflection.Missing.Value;
}
}

How to define Droppable Area in WPF?

I'm writing an application that consists of diagram and symbol palette. Symbol palette contains elements that can be placed in the diagram. Elements of diagram can be connected to each other with straight line, orthogonal line, Bezier curves,... . Applications should allow user insert a new element from symbol palette between two existing linked elements using the Drag & Drop. I would like to highlight drop target, for example by color change.

The problem is that the lines are very thin and DragOver event raises in very small area. I need to enlarge Droppable area around the lines which raises DragOver event. The line is inherited from the type System.Windows.Controls.ContentControl.

Sorting ListView in WPF

I tried to sort my listview like this: http://ift.tt/18Sdmq4

XAML:

<ListView x:Name="lvComputers" HorizontalAlignment="Left" Height="440" Margin="10,43,0,0" VerticalAlignment="Top" Width="560" SelectionChanged="lvComputers_SelectionChanged">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="120" DisplayMemberBinding="{Binding computerName}">
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Computername" Click="lvComputersColumnHeader_Click">Computername</GridViewColumnHeader>
                        </GridViewColumn.Header>
                    </GridViewColumn>
                    <GridViewColumn Width="80" DisplayMemberBinding="{Binding operatingSystem}">
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Betriebssystem" Click="lvComputersColumnHeader_Click">Betriebssystem</GridViewColumnHeader>
                        </GridViewColumn.Header>
                    </GridViewColumn>
                </GridView>
            </ListView.View> 
        </ListView>

C#:

  private void loadComputers()
        {
            lvComputers.ItemsSource = mainController.getComputers();
            lvComputers.Items.SortDescriptions.Add(new SortDescription("Computername", ListSortDirection.Ascending));
            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lvComputers.ItemsSource);
            view.SortDescriptions.Add(new SortDescription("Computername", ListSortDirection.Ascending));
            view.Filter = UserFilter;  

        }

 private void lvComputersColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader column = (sender as GridViewColumnHeader);
            string sortBy = column.Tag.ToString();
            if (listViewSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(listViewSortCol).Remove(listViewSortAdorner);
                lvComputers.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (listViewSortCol == column && listViewSortAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;

            listViewSortCol = column;
            listViewSortAdorner = new SortAdorner(listViewSortCol, newDir);
            AdornerLayer.GetAdornerLayer(listViewSortCol).Add(listViewSortAdorner);
            lvComputers.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir));
        }

"getComputers" returns a list of computers based on this class:

public class Computers
    {
        public String computerName { get; set; }
        public String operatingSystem { get; set; }
    }

UserFilter is for a searchbox. But for some reason the sorting wont work.

I tried to add this

lvComputers.Items.SortDescriptions.Add(new SortDescription("Computername", ListSortDirection.Ascending));

to

loadComputers();

but it doesnt work either.

what am i doing wrong?

WPF XAML ListBox bind to array

So i have a float array which i want to have as ItemSource in a ListBox.
Inside the ItemTemplate i have a progress bar, that should bind its Progress value to the given float value. Yet i can't ever see that the values are actually bound to the Progress property.

The xaml code (i don't know whether i'm wrong but i expected that there's a implicit cast from float to double):

<ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" BorderThickness="0">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type sys:Double}">
            <StackPanel>
                <ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center"
                                       HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/>
                <TextBlock Margin="0,3,0,3" HorizontalAlignment="Center" Text="{Binding LastUpdateTime, StringFormat='{}{0:hh:mm:ss tt}', Mode=OneWay}"
                           DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

xmlns:sys="clr-namespace:System;assembly=mscorlib"

and the property itself:

public float[] CoreLoads
{
    get { return cpuManagement.ProcessorInfo.LoadPercentages; }
}

ComboBox with null GroupDescription

I try to build an UI element witch is a ComboBox with group.

I'm almost done, here how I do it.

The data context implements this:

public interface ISelectionEditorViewModel : IEditorViewModel
{
    IEnumerable<ISelectionItemViewModel> AvailableItems { get; }
    ISelectionItemViewModel SelectedItem { get; set; }
}

Where ISelectionItemViewModel is:

public interface ISelectionItemViewModel
{
    string Group { get; }
    string Label { get; }
    ...
}

My xaml looks like this:

<UserControl.Resources>
    <CollectionViewSource x:Key="GroupedData" Source="{Binding Path=AvailableItems}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Group"/>
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</UserControl.Resources>

<ComboBox ItemsSource="{Binding Source={StaticResource GroupedData}}" SelectedValue="{Binding Path=SelectedItem}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="vm:ISelectionItemViewModel">
            <TextBlock Text="{Binding Path=Label}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

It's works like a charm.

Nice grouped items

But in some cases my items are not in any group. That it, for all item the group is null.

In this case, all items are still grouped. But the group label is empty.

Null group is nul

I try to get out of it by using a HeaderTemplateSelector in GroupStyle. The result is that if all items have null for group, the header will not be shown. I just have a list of items with no group. Ok nice.

No empty label but...

But I still have an issue, the items are not left aligned !! I would like to have this:

That it.

Controlling WPF validation manually

I have a big WPF project with a lot of input validation, I do not want to use the inbuild attribute validation anymore as it often leads to issues with when the data validation is triggered.

I would however like to just be able to manually handle errors, and still use the GUI I am given to display errors.

All presentation objects have IDataErrorInfo

So is it possible to manually set the error text and handle when it is shown or not.

Example

So when I press Save on my View something like this would happen

private void Validate()
{
    bool success = true;

    If(a == null)
    {
        a.ValidationError = true;
        a.ValidationText = "A is required!"
        success = false;
    }
    else
    {
      a.ValidationError = false;
    }

    return success;
}

So if A is null, an error is marked and the tooltip shows my "A is required!" text

Is it possible to control it completely manually and just loop through my data at specified times and show errors.

Windows 10 Universal App - ListView Update from Background Thread

I have a strange problem here. We develop a Windows 10 Universal App and now I want to update my listview when I add new value. But unfortunately it wont work and I dont really know why. When I add new value it won't update my list view.

The data comes from a background-thread (REST-Request against Server) and therefore I know, I should use something that runs the "add-functionality" on the UI-Thread.

First of all I declared a IProgress and my collection:

private List<dtoGemeinde> _listeGemeinden = new List<dtoGemeinde>();


public List<dtoGemeinde> GemeindenCollection
{
            get { return this._listeGemeinden; }
}

IProgress<dtoGemeinde> prog;

prog = new Progress<dtoGemeinde>(UpdateListViewUI);

This is the "UpdateListViewUI" method:

 public void UpdateListViewUI(dtoGemeinde dto)
 {
           _listeGemeinden.Add(dto);

            this.listViewGemeinden.ItemsSource = GemeindenCollection;
 }

And this is the callback method which is called when the background thread, which loads the data from the server, is finished:

 public async void onCallBackGemeinden(List<dtoGemeinde> listeGemeinden)
        {
            if (listeGemeinden != null && listeGemeinden.Count > 0)
            {
                this.progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                foreach (dtoGemeinde dto in listeGemeinden)
                {
                    await listViewGemeinden.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => prog.Report(dto));              
                }                          
            }
            else
            {
                await new MessageDialog("Data cant be load", "Error").ShowAsync();
            }
        }

Programmatically Binding Name ItemsControl

I create programmatically a grid of rectangles and each rectangle has a Label inside it. I detect which rectangle has been clicked using Event Command. My problem is that if I try to bind the rectangle Name I get this error: MarkupExtensions are not allowed for Uid or Name property values, so '{Binding ID}' is not valid So I can retrive the name only if I click on the Label. Is there a solution for this problem? My XAML:

<ItemsControl ItemsSource="{Binding CaskList}" HorizontalAlignment="Left" VerticalAlignment="Top">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Width="1680" Height="800">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="MouseLeftButtonDown" >
                                    <cmd:EventToCommand Command="{Binding SelCaskCommand}" PassEventArgsToCommand="True" />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </Canvas>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
                        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Rectangle Stroke="Black" Width="64" Height="64" Fill="{Binding Color}" ></Rectangle>
                            <Label Content="{Binding ID}" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

DrawingContext, Text, CultureInvariant, Printing, Windows10

I have encountered a problem when testing printing from application on Windows 10 (Pro Insider preview EN_US 10130). I found out that my code that prints document is failing and problem lies in drawingContext.DrawText() call. I found that "CultureInfo.InvariantCulture" has to be changed to something different, for example new CultureInfo("en-US") otherwise my printout fails.

Is there a reason why it is failing, or is it a bug in Windows 10? This solution worked fine so far on systems with Windows XP, 7, 8 and 8.1. Here is code that I use:

var visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
    context.DrawText(
        new FormattedText(
            "my text",
            CultureInfo.InvariantCulture, // new CultureInfo("en-US")
            FlowDirection.LeftToRight,
            new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
            15,
            new SolidColorBrush(Color.FromRgb(0, 39, 91))),
        new Point(10, 20));
}

get item from treeView c#

I have a TreeVe

<TreeView Name="files" Margin="0,0,569,108" Grid.Row="1" ItemsSource="{Binding s1}">
                        <TreeView.ItemTemplate>
                            <HierarchicalDataTemplate ItemsSource="{Binding Members}" >
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="{Binding Name}" />
                                </StackPanel>
                                <HierarchicalDataTemplate.ItemTemplate>
                                    <DataTemplate>
                                        <CheckBox Name="CheckBox111" Checked="FileCheckBox_Checked" Unchecked="FileCheckBox_Unchecked">
                                            <ContentPresenter>
                                                <ContentPresenter.Content>
                                                    <StackPanel Orientation="Horizontal">
                                                        <Image Source="file.jpg" Margin="5,0,5,0" Width="20" Height="20" />
                                                        <TextBlock Text="{Binding Name}" />
                                                    </StackPanel>
                                                </ContentPresenter.Content>
                                            </ContentPresenter>
                                        </CheckBox>
                                    </DataTemplate>
                                </HierarchicalDataTemplate.ItemTemplate>
                            </HierarchicalDataTemplate>

                        </TreeView.ItemTemplate>
                    </TreeView>

and i want to check all the checkBoxs in the code-behind:

   private void AllFilesCheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (Object item in (files as ItemsControl).Items)
       {
           TreeViewItem t = files.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

           foreach (Object item1 in t.Items)
           {
              // TreeViewItem t2 = item1 as TreeViewItem;
             //  CheckBox t1 =item1 as CheckBox;
           }
       }}

But I can not get access to the checkBox... I do not know how to get access to it.

thank you.

how to get count of number of opened windows in WPF

I have a requirement that, if one window is opened then user can not allow to open other window, for that I have tried following code.

if(System.Windows.Application.Current.Windows.Count == 0)

{

-- My code

}

I am checking for currently opened window count, if it is greater then 1 then user can not open other window and that I will mention inside if statement,

but when I run this code it gives me the error "Object reference not set to an instance of an object."

Any Solution

Wpf Caliburn Micro: binding click event of faked captioned Rectangle

I use VS2013, Wpf 4.5 and Caliburn Micro. I want to use a Rectangle and to put TextBlock in it. I found a solution here in StackOverflow: put the rectangle and the textblock in a grid. It works.

Then I want to catch click event if user click on the rectangle. So I add x:Name="ClickMe" attribute in tag to bind click event to view model. It works, but only if the mouse points on non-text area of rectangle. As soon as the mouse pointer is on TextBlock area, the click event is ignored!

My first try: bind the TextBlock using x:Name="ClickText1" to event handler ClickText1(). It doesn't work. It seems TextBlock has no Click event.

My second try: I tried to put the TextBlock in a StackPanel, bind the StackPanel using x:Name="ClickStack" and the event handler ClickStack() will calls the ClickMe(). It doesn't work since the ClickStack() is called as soon as the application is started and before he view is shown. So my try is failed!

What I want: the whole rectangle area should be clicable (and raise click event) regardless text-area or non-text-area and the click event can be bound to ONE event handler in view model. All should work in caliburn micro pattern and no code-behind.

I attach my sample code below. Please feel free to modify it and show me how to solve it. You may also suggest me other simple way to put text on rectangle without using grid. But please don't suggest me to use Button control due to requirement of my project. Thank you in advance.

The View:

<UserControl x:Class="CMWpfShapeWithCaption.Views.ShellView"
         xmlns="http://ift.tt/o66D3f"
         xmlns:x="http://ift.tt/mPTqtT"
         xmlns:d="http://ift.tt/pHvyf2"
         xmlns:mc="http://ift.tt/pzd6Lm"
         d:DesignHeight="300"
         d:DesignWidth="300"
         mc:Ignorable="d">
    <Grid Width="300"
          Height="300"
          ShowGridLines="False">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20*" />
            <ColumnDefinition Width="20*" />
            <ColumnDefinition Width="20*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20*" />
            <RowDefinition Height="20*" />
            <RowDefinition Height="20*" />
        </Grid.RowDefinitions>
        <Rectangle x:Name="ClickMe"
                   Grid.Row="1"
                   Grid.Column="1"
                   Fill="Aqua" />
        <StackPanel Grid.Row="1"
                    Grid.Column="1"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center">
             <TextBlock x:Name="ClickText1"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Text="{Binding Path=Text1}"
                        TextWrapping="Wrap" />
             <TextBlock HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Text="{Binding Path=Text2}"
                        TextWrapping="Wrap" />
         </StackPanel>
     </Grid>
</UserControl>

The view model:

using System;
using System.Windows;
using Caliburn.Micro;

namespace CMWpfShapeWithCaption.ViewModels
{
    public class ShellViewModel : PropertyChangedBase
    {
        public ShellViewModel()
        {
            Text1 = "Text1";
            Text2 = "Text2";
        }
        public String Text1 { get; set; }
        public String Text2 { get; set; }

        // Problem: this will be called only if Mouse points non-text area of grid
        // Target: This should be called regardless non-text or text-area,
        // as long as the mouse is clicked within rectangle area.
        public void ClickMe()
        {
            MessageBox.Show("Panel is clicked");
        }

        // This trick doesn't work at all.
        // It seems TextBlock has no click event?
        public void ClickText1()
        {
            ClickMe();
        }
    }
}

How can play video as a wallpaper like dreamscreen by C#

how the dreamscreen implemented by C# ? I want to play a video front the wallpaper but blow the icon on the desktop.

user control numeric pad

i had made a user control numeric pad in wpf. i want to know when i placed a control over the form. when i pressed any numeric button then it should be entered in the focused area. how to do it this is my xaml script enter code here

        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Button Name="btn2" Content="2" Focusable="False"  FontSize="26"  HorizontalAlignment="Stretch"   VerticalAlignment="Stretch" Grid.Column="1" Grid.Row=" 1" />
    <Button Name="btn1" Content="1" Focusable="False" FontSize="26" HorizontalAlignment="Stretch"   Grid.Row="1" VerticalAlignment="Stretch" BorderBrush="DarkGray"  BorderThickness="4,2,2,8"  />
    <Button Name="btn3" Content="3" Focusable="False" FontSize="26" Grid.Column="2" Foreground="White"  HorizontalAlignment="Stretch"   Grid.Row="1" VerticalAlignment="Stretch"  />
    <Button Name="btn4" Content="4" Focusable="False"  FontSize="26" HorizontalAlignment="Stretch"   Grid.Row="2" VerticalAlignment="Stretch"  />
    <Button Name="btn5" Content="5" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch"   Grid.Row="2" VerticalAlignment="Stretch"  />
    <Button Name="btn6" Content="6" Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch"  Grid.Row="2" VerticalAlignment="Stretch"  />
    <Button Name="btn7" Content="7" Focusable="False" FontSize="26" HorizontalAlignment="Stretch"   Grid.Row="3" VerticalAlignment="Stretch"  />
    <Button Name="btn8" Content="8" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch"  Grid.Row="3" VerticalAlignment="Stretch"  />
    <Button Name="btn9" Content="9" Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch"   Grid.Row="3" VerticalAlignment="Stretch"   />
    <Button Name="btn0" Content="0" Focusable="False" FontSize="26" HorizontalAlignment="Stretch"  Grid.Row="4" VerticalAlignment="Stretch"  />
    <Button Name="btn00" Content="00" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch"   Grid.Row="4" VerticalAlignment="Stretch"  />
    <Button Name="btn_dot" Content="." Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch"   Grid.Row="4" VerticalAlignment="Stretch"  />
    <Button Name="btn_temp1" Content="Button" Focusable="False" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" />
    <Button Name="btn_temp2" Content="Button" Focusable="False" Grid.Column="1" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" />
    <Button Name="btn_temp3" Content="Button" Focusable="False" Grid.Column="2" HorizontalAlignment="Stretch"   VerticalAlignment="Stretch"  />
</Grid>

``

How to determine whether two FlowDocuments have the same content?

I'm creating a small text editor using a RichTextBox in WPF. When the editor is closed I'd like to ask the user if he really wants to close, but ONLY IF there are unsaved changes. I made a copy of the RTB's original FlowDocument and want to compare it in the RTB.SelectionChanged event with the current FlowDocument of the RTB to see if the user has changed the document. If so, a flag is set that tells me there are some unsaved changes. However, I dont't really know how to compare the two FlowDocuments, i.e. how to determine whether their contents are the same or not (including formatting such as fontsize, -weight, textdecorations...). I tried .Equals but that doesn't seem to work at all. I'm aware of how to get the plain text aut of a RTB and compare that but it's important to me to also check whether the formatting of the text has changed or not.

I'd really appreciate your help! Thanks!

WPF Textbox TwoWay binding in datatemplate not updating the source even on LostFocus

I have an ObservableCollection<string> Tags as part of a custom object. I bind it to a DataTemplate in order to show all tags to the user with the following code:

<StackPanel DockPanel.Dock="Top" Margin="15,0,15,0" Orientation="Horizontal">
    <Label Content="Tags:" FontSize="14" Foreground="{StaticResource HM2LightTextBrush}"/>
    <Grid>
        <ItemsControl Name="PanelPreviewNoteTags" ItemsSource="{Binding ElementName=lbNotesQuickView, Path=SelectedItem.Tags}" Margin="3,0" Visibility="Collapsed">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="1" BorderBrush="#676B6E" Margin="3,0">
                        <Label Content="{Binding .,Mode=OneWay}" Foreground="{StaticResource HM2LightTextBrush}"/>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <ItemsControl Name="PanelEditNoteTags" ItemsSource="{Binding ElementName=lbNotesQuickView, Path=SelectedItem.Tags}" Margin="3,0" Visibility="Collapsed">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="1" BorderBrush="#676B6E" Margin="3,0">
                        <StackPanel Orientation="Horizontal">
                            <TextBox Text="{Binding ., Mode=TwoWay}"/>
                            <Button Style="{StaticResource RibbonButton}" Click="ButtonRemoveTagClick" Tag="{Binding}">
                                <Image Height="16" Width="16" Source="/Poker Assistant;component/Resources/fileclose.png" />
                            </Button>
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</StackPanel>

Adding and removing items from the ObservableCollection works as expected.

In code I switch between edit and view mode by setting the Visibility of the corresponding PanelEditNoteTags and PanelPreviewNoteTags. This all good and working. But when I enter the edit mode and start typing new values for the tags in the TextBox the source doesn't get updated. I certainly know that the LostFocus event is raised when I press my Save button. I tried all UpdateSourceTrigger values, still the same.

Is it a problem related to two controls binding at the same time to the same value - the Label from PanelPreviewNoteTags and the TextBox from PanelEditNoteTags?

What am I missing here?

Add Button on Each Row in DataGrid WPF in Code Behind

I am dynamically add the column for the datagrid,

Dim oName_Binding As Binding = New Binding("Order_Name")
oName_Binding.Mode = BindingMode.TwoWay
oName_Binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged

Dim dgcombo As DataGridComboBoxColumn = New DataGridComboBoxColumn()
dgcombo.Header = "Order"
dgcombo.ItemsSource = lstOrder
dgcombo.TextBinding = oName_Binding
dgcombo.DisplayMemberPath = "Order_Name"
dgcombo.SelectedValuePath = "Order_ID"
dgv.Columns.Add(dgcombo)

I would like to add the button on Each Row. Please suggest me...

dimanche 28 juin 2015

Maintaining same recent colours list for WPF RadColorPicker in the application

I am using RadColorPicker in my application at no. of different places. As of now, if I open the RadColorPicker anywhere in the application, it won't maintain any recent colors from the RadColorPicker which I opened at a different place.

What could be the best way to handle this?

C# WPF Sum datagrid column to label

I am having problems adding up all of the values in a WPF Datagrid column to a label upon a change event (probably SelectionChanged). I have this code:

private void tblData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
        decimal total = 0;

        foreach(DataRowView rowView in (DataView)this.tblData.ItemsSource)
        {
            total += (decimal)rowView["Total"];
        }
        lblTotal.Content = total.ToString();
}

But it breaks my program, it throws a 'System.InvalidCastException'. Can anyone please look at my code and help me figure out what I am doing wrong?

com event not received when host in wpf container

A custom COM component, the component registered under the WinForm event, can normal callback, But when you use the COM component and register the event in WPF, the COM Control's event could not normally be triggered.

Draw logarithmic lines in WPF Graph

I have to implement Frequency vs Gain Graph. X axis have logarithmic divisions like 10, 100, 1k and 2k , between each of the them there are other dotted line divisions. I am using WPF Tool kit to draw the graph. Now, I can I implement these dotted lines for x axis, also the dotted line are same between each main x axis values.

Move selected row to bottom or last row of datagrid WPF C#

enter image description hereSo I'm currently doing an automated IQ exam for our HR department. I'm using C# as my P-language and WPF as app foundation. My questions are stored on a mysql database and binded on a datagrid.

My question is, is there a way for me to move a row to the last row? The idea is, when an examiner skips a question, that question goes to the last row of the datagrid. Thanks in advance!

Edit: I've added a picture to explain my idea. Hope it helps! enter image description here

WPF, create Custom DataGridTextColumn to Prevent unwanted Character

i newbie to WPF, i want to prevent user to input character, eg. character "-", so i created custom DataGridTextColumn with following code :

public class DataGridNumericColumn : DataGridTextColumn
{
    protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
    {
        var textBox = (TextBox) editingElement;
        textBox.PreviewTextInput += OnPreviewTextInput;
        return base.PrepareCellForEdit(editingElement, editingEventArgs);
    }


    private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var textBox = (TextBox)sender;
        if (e.Text == "-")
            return;
        if (!this.IsNumeric(e.Text))
            e.Handled = true;
    }
}

and XAML :

<ZF:ZFDataGrid
        Grid.Row="4" Grid.Column="0" 
        HorizontalAlignment="Stretch" VerticalAlignment="Top"
        HorizontalContentAlignment="Stretch"
        VerticalContentAlignment="Stretch"
        CanUserAddRows="True"
        CanUserDeleteRows="False"
        CanUserResizeRows="False"
        CanUserReorderColumns="False"
        CanUserSortColumns="False"
        IsSynchronizedWithCurrentItem="True"
        SelectionUnit="Cell"
        SelectionMode="Single"
        Margin="3,3,3,0" 
        AutoGenerateColumns="False"
        AlternatingRowBackground="WhiteSmoke"
        RowHeaderWidth="30"
        FontSize="18"
        ItemsSource="{Binding POSModel}">
    <ZF:DataGridNumericColumn Header="Qty" Width="80" />
</ZF:ZFDataGrid>

the Custom DataGridNumericColumn work well, except when i press the character for the first time. if i press F2 to edit or double click the column and then press the key, everything works well.

but if i press the key without editing the cell first, the custom DataGridNumericColumn not work.

i put breakpoint on PrepareCellForEdit, and the coding works. but method OnPreviewTextInput works the second time when i press the key. not the first one.

can anyone give me another solution ?

EDITED:

protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
    {
        var textBox = (TextBox) editingElement;
        textBox.PreviewTextInput += OnPreviewTextInput;
        textBox.TextChanged += OnTextChanged; //change here
        return base.PrepareCellForEdit(editingElement, editingEventArgs);
    }

this code only run ONCE, the rest will be handled by OnPreviewTextInput

  private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        var textBox = (TextBox)sender;

        if (textBox.Text.Contains("-"))
        {
            textBox.TextChanged -= OnTextChanged;
            textBox.Text = "";
        }
    }

DataSet not updating Database

I'm having a problem with updating the database using a dataset.

The dataset and Adapters are generated by Visual Studio.

I've already tried many variations of calling the Update method but changes are always gone when restarting the program.

I'm using WPF for the user interface and DataGrids to visualize and modify the data.

Here is the markup:

<Window xmlns="http://ift.tt/o66D3f"
                xmlns:x="http://ift.tt/mPTqtT"
                xmlns:local="clr-namespace:GUI"
                x:Class="GUI.MainWindow"
                Title="MainWindow"
                Loaded="Window_Loaded">
    <Window.Resources>
        <local:FábricaVeículosDataSet x:Key="fábricaVeículosDataSet" />
        <CollectionViewSource x:Key="clientesViewSource"
                              Source="{Binding Clientes, Source={StaticResource fábricaVeículosDataSet}}" />
        <!--snip-->
    </Window.Resources>
    <TabControl TabStripPlacement="Left">
        <TabItem Header="Clientes">
            <Grid Background="#FFE5E5E5"
                  DataContext="{StaticResource clientesViewSource}">
                <DataGrid x:Name="clientesDataGrid"
                          AutoGenerateColumns="False"
                          EnableRowVirtualization="True"
                          ItemsSource="{Binding}"
                          RowDetailsVisibilityMode="VisibleWhenSelected">
                    <DataGrid.Columns>
                        <DataGridTextColumn x:Name="cod_ClienteColumn"
                                            Binding="{Binding Cod_Cliente}"
                                            Header="Cod Cliente"
                                            IsReadOnly="True"
                                            Width="SizeToHeader" />
                        <DataGridTextColumn x:Name="nom_ClienteColumn"
                                            Binding="{Binding Nom_Cliente}"
                                            Header="Nom Cliente"
                                            Width="SizeToHeader" />
                        <DataGridTextColumn x:Name="end_ClienteColumn"
                                            Binding="{Binding End_Cliente}"
                                            Header="End Cliente"
                                            Width="SizeToHeader" />
                        <DataGridTextColumn x:Name="fon_ClienteColumn"
                                            Binding="{Binding Fon_Cliente}"
                                            Header="Fon Cliente"
                                            Width="SizeToHeader" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </TabItem>
        <!--snip-->
    </TabControl>
</Window>

And code behind:

    FábricaVeículosDataSet fábricaVeículosDataSet;
    ClientesTableAdapter clientesTableAdapter;
    /*snip*/

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.fábricaVeículosDataSet = ((GUI.FábricaVeículosDataSet)(this.FindResource("fábricaVeículosDataSet")));

        // Load data into the table Clientes. You can modify this code as needed.
        this.clientesTableAdapter = new ClientesTableAdapter();
        clientesTableAdapter.Fill(fábricaVeículosDataSet.Clientes);
        var clientesViewSource = ((CollectionViewSource)(this.FindResource("clientesViewSource")));
        clientesViewSource.View.MoveCurrentToFirst();
        fábricaVeículosDataSet.Clientes.RowChanging += Clientes_RowChanging;
        fábricaVeículosDataSet.Clientes.RowDeleting += Clientes_RowChanging;
        /*snip*/
    }

    /*neither of these work, I'm not using them together, just put both to show what I tried*/
    void Clientes_RowChanging(object sender, System.Data.DataRowChangeEventArgs e)
    { this.clientesTableAdapter.Update(fábricaVeículosDataSet.Clientes); }

    private void clientesDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    { this.clientesTableAdapter.Update(fábricaVeículosDataSet.Clientes); }

Multiple Showdialog

I have a main window which calls another window with ShowDialog(), lets call it window A. Window A calls another window also with ShowDialog(), lets call it window B.

Whenever window B is closed using Close(), I want Window A to be shown, not the main window.

How am I supposed to do that? I already tried using this.Owner, this.Focus, etc. none of them work.

Note: I am using WPF

here is my code from main window:

WindowsA WA = new WindowsA(); WA.showDialog();

at WindowsA, i call another window WindowsB:

WindowsB WB = new WindowsB(); WB.showDialog();

from WindowsB, I pressed button to close:

Close();

Where should I put the owner?

Bind byte array to image in windows phone 8.1 xaml

I bind byte array to image source in my windows phone application.

XAML:

 <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
                    <Image Source="{Binding EventPicture}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
                </Border>

It's a part of item template of ListView in HubSection. Items are bind from view model and it got them from service in json format.

Data retrieving code:

public async Task<ObservableCollection<SocialEvent>> GetSocialEventsAsync()
{
    var socialEvents = new ObservableCollection<SocialEvent>();
    var httpClient = new HttpClient();
    var jsonResponse = await httpClient.GetStringAsync(string.Format("{0}{1}",BaseUrl,"socialevents/1"));
    var eventArray = JsonConvert.DeserializeObject<SocialEvent[]>(jsonResponse);
    foreach (var evnt in eventArray)
    {
        socialEvents.Add(evnt);
    }
    return socialEvents;
}

The problem is that I get this in my application enter image description here

I'm 100% sure that images is in the right format, at least I checked the base64 string in json response. Also I tried to re-size image and many other things with layout. I wrote a converter from byte[] to ImageSource but there was no result too.

Any ideas guys?

P.S. Sorry for my English, I hope you understand me ;)

How to save or convert a byte array or MemoryStream as wav file in WPF? (kinect audio source)

I have an idea that get them of AudioBasics-WPF Kinect v2 sample code: we can save each audio frame as a single wav file: subFrame.CopyFrameDataToArray(this.audioBuffer); and then collect them to a single wav file.

My question how to save or convert a byte array or MemoryStream as wav file in WPF?

Click-through WPF window + content while still catching events

Basically what I'm trying to do is have a window with controls that responds to the mouse and keyboard, but does not take focus. I've been looking into hooking into the window events to catch them or using the preview events and not handling them, but whatever I do, the window either fires the mouse and keyboard events and takes focus or does not do anything at all.

Is it possible to hook to the mouse/keyboard events for a window manually while still passing the events to any window (other applications too) behind it?

How to insert rows into Mysql database without duplicate?

When i want to insert a row into my MySql database 4 rows will be inserted instead of 1. Could you help me?

    MySqlConnection con = new MySqlConnection(cs);
                    string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
                    MySqlCommand com = new MySqlCommand(Query, con);
                    com.ExecuteNonQuery();

Type of object to cast to when parsing DataGrid.SelectedItems (bound to a MySql DataTable)

I have a simple C# / WPF application that reads a MySql database into a DataGrid.

    <DataGrid  Height="470" Width="800" AutoGenerateColumns="True" CanUserResizeColumns="True" CanUserReorderColumns="True" x:Name="DgrReadWrite" ItemsSource="{Binding ''}"  HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" />

I load the Sql data into it like this:

    string connStr = Service.getConnectionString();

        string sql = "SELECT * FROM adat";
        try
        {
            MySqlConnection connection = new MySqlConnection(connStr);
            MySqlCommand cmdSel = new MySqlCommand(sql, connection);

            MySqlDataAdapter da2 = new MySqlDataAdapter(cmdSel);
            da2.Fill(this.dt2);
            DgrReadWrite.DataContext = dt2;
        }
        catch (Exception ex)
        {
            MessageBox.Show("MySQL kapcsolódási hiba!", "Hiba!", MessageBoxButton.OK, MessageBoxImage.Error);
        }

When I press the delete button, this would happen:

   for (int i = 0; i < this.dt2.Rows.Count; i++)
        {

            // looping through DgrReadWrite.SelectedItems.Cast<SomethingReadable??>
            if (somethingReadable[0] == this.dt2.Rows[i][0].ToString())
            {   
                dt2.Rows[i].Delete();
                DgrReadWrite.Items.Refresh();
            }
        }

My question: what type should I cast the selected items so I can make sense of them in the method? Thank you in advance.

WPF TreeViewItem subclass does not display text/data template

I made a subclass of TreeViewItem so I could have some custom fields, I have also created a style for the subclass but it doesn't display the text or the border attributes properly.

Xaml for the user control

<UserControl x:Class="Project.ProfilesPanel"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             xmlns:mc="http://ift.tt/pzd6Lm" 
             xmlns:d="http://ift.tt/pHvyf2"
             xmlns:controls="clr-namespace:Project"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.Resources>
            <!--The HierarchicalDataTemplate used by TreeViewItems
                in the second level of the TreeView.-->
            <HierarchicalDataTemplate x:Key="Level2Data" ItemsSource="{Binding Path=Items}">
                <Border>
                    <TextBlock Text="{Binding Path=Title}" VerticalAlignment="Center" />
                </Border>
            </HierarchicalDataTemplate>

            <!--The HierarchicalDataTemplate used by TreeViewItems
                in the first level of the TreeView.-->
            <HierarchicalDataTemplate x:Key="Level1Data"
                  ItemsSource="{Binding Path=Items}"
                  ItemTemplate="{StaticResource Level2Data}">
                <Border Height="20">
                    <TextBlock Text="{Binding Path=Title}" VerticalAlignment="Center" />
                </Border>
            </HierarchicalDataTemplate>

            <Style TargetType="controls:MenuItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                <Setter Property="Focusable" Value="True" />
                <Setter Property="IsExpanded" Value="True" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="controls:MenuItem">
                            <StackPanel>
                                <Grid x:Name="GridBd" Margin="1">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition />
                                    </Grid.RowDefinitions>
                                    <Border x:Name="TrueBd" Grid.Row="0" Grid.ColumnSpan="2">
                                        <ContentPresenter x:Name="SomeHeader"
                                                ContentTemplate="{TemplateBinding Property=HeaderTemplate}" />
                                    </Border>
                                    <ToggleButton IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}"
                                          ClickMode="Press" Name="Expander">
                                        <ToggleButton.Style>
                                            <Style TargetType="ToggleButton">
                                                <Setter Property="UIElement.Focusable" Value="false" />
                                                <Setter Property="FrameworkElement.Width" Value="16" />
                                                <Setter Property="FrameworkElement.Height" Value="16" />
                                                <Setter Property="Control.Template">
                                                    <Setter.Value>
                                                        <ControlTemplate TargetType="ToggleButton">
                                                            <Border Padding="5,5,5,5" Background="#00FFFFFF"
                                                                Width="16"
                                                                Height="16">
                                                                <Path Fill="#00FFFFFF"
                                                                    Stroke="Black"
                                                                    Name="ExpandPath">
                                                                    <Path.Data>
                                                                        <PathGeometry Figures="M0,0L0,6L6,0z" />
                                                                    </Path.Data>
                                                                    <Path.RenderTransform>
                                                                        <RotateTransform Angle="135"
                                                                        CenterX="3"
                                                                        CenterY="3" />
                                                                    </Path.RenderTransform>
                                                                </Path>
                                                            </Border>
                                                            <ControlTemplate.Triggers>
                                                                <Trigger Property="UIElement.IsMouseOver" Value="True">
                                                                    <Setter TargetName="ExpandPath"
                                                                        Property="Shape.Stroke"
                                                                        Value="#FF1BBBFA" />
                                                                    <Setter TargetName="ExpandPath"
                                                                        Property="Shape.Fill"
                                                                        Value="#00FFFFFF" />
                                                                </Trigger>
                                                                <Trigger Property="ToggleButton.IsChecked" Value="True">
                                                                    <Setter TargetName="ExpandPath" Property="UIElement.RenderTransform">
                                                                        <Setter.Value>
                                                                            <RotateTransform Angle="180"
                                                                                 CenterX="3"
                                                                                 CenterY="3" />
                                                                        </Setter.Value>
                                                                    </Setter>
                                                                    <Setter TargetName="ExpandPath"
                                                                        Property="Shape.Fill"
                                                                        Value="Black" />
                                                                    <Setter TargetName="ExpandPath"
                                                                        Property="Shape.Stroke"
                                                                        Value="Black" />
                                                                </Trigger>
                                                            </ControlTemplate.Triggers>
                                                        </ControlTemplate>
                                                    </Setter.Value>
                                                </Setter>
                                            </Style>
                                        </ToggleButton.Style>
                                    </ToggleButton>
                                    <Border x:Name="Bd"
                                        HorizontalAlignment="Stretch"
                                        BorderThickness="{TemplateBinding Border.BorderThickness}"
                                        BorderBrush="{TemplateBinding Border.BorderBrush}"
                                        Padding="{TemplateBinding Control.Padding}"
                                        Background="{TemplateBinding Panel.Background}"
                                        SnapsToDevicePixels="True"
                                        Grid.Column="1">
                                        <ContentPresenter x:Name="PART_Header"
                                            Content="{TemplateBinding HeaderedContentControl.Header}"
                                            ContentTemplate="{TemplateBinding HeaderedContentControl.HeaderTemplate}"
                                            ContentStringFormat="{TemplateBinding HeaderedItemsControl.HeaderStringFormat}"
                                            ContentTemplateSelector="{TemplateBinding HeaderedItemsControl.HeaderTemplateSelector}"
                                            ContentSource="Header"
                                            HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                                            SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                                    </Border>
                                    <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Row="1" />
                                </Grid>
                            </StackPanel>
                            <ControlTemplate.Triggers>
                                <Trigger Property="TreeViewItem.IsExpanded" Value="False">
                                    <Setter TargetName="ItemsHost" Property="UIElement.Visibility" Value="Collapsed" />
                                </Trigger>
                                <Trigger Property="ItemsControl.HasItems" Value="False">
                                    <Setter TargetName="TrueBd" Property="Background" Value="#FAFAFAFA"/>
                                    <Setter TargetName="Expander" Property="UIElement.Visibility" Value="Hidden" />
                                </Trigger>
                                <Trigger Property="ItemsControl.HasItems" Value="True">
                                    <Setter TargetName="TrueBd" Property="Background" Value="LightSteelBlue"/>
                                </Trigger>
                                <Trigger Property="TreeViewItem.IsSelected" Value="True">
                                    <Setter TargetName="TrueBd"
                                        Property="Background"
                                        Value="LightSkyBlue" />
                                    <Setter Property="TextElement.Foreground"
                                        Value="White" />
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition SourceName="PART_Header" Property="IsMouseOver" Value="True"/>
                                        <Condition Property="TreeViewItem.IsSelected" Value="False" />
                                    </MultiTrigger.Conditions>                 
                                        <Setter TargetName="TrueBd"
                                            Property="Background"
                                            Value="SteelBlue" />
                                        <Setter Property="TextElement.Foreground"
                                            Value="White" />
                                </MultiTrigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="TreeViewItem.IsSelected" Value="True" />
                                        <Condition Property="Selector.IsSelectionActive" Value="False" />
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="TrueBd"
                                        Property="Background"
                                        Value="LightSkyBlue" />
                                    <Setter Property="TextElement.Foreground"
                                        Value="White" />
                                </MultiTrigger>
                                <Trigger Property="UIElement.IsEnabled" Value="False">
                                    <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

        </Grid.Resources>

        <TreeView Name="trvMenu" ItemsSource="{Binding Items}" HorizontalAlignment="Stretch"
            ItemTemplate="{StaticResource Level1Data}"
            MouseRightButtonDown="TV_MouseRightButtonUp" />
    </Grid>
</UserControl>

And the Xaml.cs looks like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for ProfilesPanel.xaml
    /// </summary>
    public partial class ProfilesPanel : UserControl
    {
        public ProfilesPanel()
        {
            InitializeComponent();
            MenuItem sears = new MenuItem() { Title = "Sears", Type = "Org" };
            sears.Items.Add(new MenuItem() { Title = "Child item #1", Type = "Profile" });
            sears.Items.Add(new MenuItem() { Title = "Child item #2", Type = "Profile" });
            trvMenu.Items.Add(sears);

            MenuItem macys = new MenuItem() { Title = "Macys", Type = "Org" };
            macys.Items.Add(new MenuItem() { Title = "Child item #1", Type = "Profile" });
            macys.Items.Add(new MenuItem() { Title = "Child item #2", Type = "Profile" });
            macys.Items.Add(new MenuItem() { Title = "Child item #3", Type = "Profile" });
            macys.Items.Add(new MenuItem() { Title = "Child item #4", Type = "Profile" });
            trvMenu.Items.Add(macys);
        }

        private void TV_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            trvMenu.Items.Remove(trvMenu.SelectedItem);
        }
    }

    public partial class MenuItem : TreeViewItem
    {
        public string Title { get; set; }
        public string Type { get; set; }
    }
}

The style was developed with a two level Tree in mind where the first level has a larger border with a background color. The children have a different background color. The tree is displayed with the style and background colors but the border size and text defined in the HierarchicalDataTemplates do not show up correctly. The text field is blank.

My suspicion is that I am missing something in the style I am using to display the MenuItem, but I am fairly new to WPF so I don't know what I am missing.

Click through ListBox to underlying Control

Hi I want to click through my listBox (click on empty space) and want the click on the underlying border control. I'm really sure that I have done this in the past using {x:Null} as the Background for a control. But this time it doesn't work.

Any hint why?

 <Grid>
     <Border x:Name="BrushBorder" Background="{Binding ActualBrush}" Margin="7,0" Height="10"
             VerticalAlignment="Top" Cursor="Pen">
         <dxmvvm:Interaction.Behaviors>
             <dxmvvm:EventToCommand EventName="MouseDown" Command="{Binding NewGradientStopCommand}" PassEventArgsToCommand="True" />
         </dxmvvm:Interaction.Behaviors>
     </Border>
     <ListBox x:Name="GradientStopListBox" ItemsSource="{Binding GradientStops}" SelectedItem="{Binding ActualGradientStop}"
              HorizontalContentAlignment="Stretch"
              VerticalContentAlignment="Stretch" 
              Background="{x:Null}" BorderBrush="{x:Null}">

Accessing controls in control template

I have defined a style for a control so that it's content is a combonation of different controls.

<Style x:Key="TagSetting" TargetType="CheckBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CheckBox}">
                <StackPanel Orientation="Horizontal" Margin="0,0,0,5">
                    <CheckBox x:Name="chkTag" Focusable="False"/>
                    <ComboBox x:Name="cbbTagAction" Width="65" Margin="0,0,5,0">
                        <ComboBoxItem Content="Clear"/>
                        <ComboBoxItem Content="Tag"/>
                    </ComboBox>
                    <TextBlock x:Name="lblTag" Text="{TemplateBinding Content}" VerticalAlignment="Center"/>
                </StackPanel>
                <ControlTemplate.Triggers>
                    <Trigger SourceName="chkTag" Property="IsChecked" Value="True">
                        <Setter TargetName="cbbTagAction" Property="IsEnabled" Value="True"/>
                        <Setter TargetName="cbbTagAction" Property="SelectedIndex" Value="1"/>
                        <Setter TargetName="lblTag" Property="IsEnabled" Value="True"/>
                    </Trigger>
                    <Trigger SourceName="chkTag" Property="IsChecked" Value="False">
                        <Setter TargetName="cbbTagAction" Property="IsEnabled" Value="False"/>
                        <Setter TargetName="cbbTagAction" Property="SelectedIndex" Value="-1"/>
                        <Setter TargetName="lblTag" Property="IsEnabled" Value="False"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And I need to access the ComboBox cbbTagAction in code so I can set the selected index. I have many of these CheckBoxes.

<CheckBox x:Name="chkAlbum" Style="{StaticResource TagSetting}" Content="album"/>
<CheckBox x:Name="chkAlbumArtists" Style="{StaticResource TagSetting}" Content="album artists"/>
<CheckBox x:Name="chkArtists" Style="{StaticResource TagSetting}" Content="artists"/>
<CheckBox x:Name="chkArtwork" Style="{StaticResource TagSetting}" Content="artwork"/>
<!-- It goes on... --->

How can I access the ComboBox for each of these CheckBoxes so I can set the selected index in C# code (not XAML)?