Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

Property editing not available

$
0
0

I have lost the ability to edit properties using the property editor in VS 2010 Pro.

The XAML that shows this problems is:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SMOExplorer"
    xmlns:smo="clr-namespace:Microsoft.SqlServer.Management.Smo;assembly=Microsoft.SqlServer.Smo"
    Title="MainWindow" Height="545" Width="971" Loaded="Window_Loaded"><Window.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="\Dictionaries\TableDictionary.xaml"></ResourceDictionary><ResourceDictionary Source="\Dictionaries\StoredProcedureDictionary.xaml"></ResourceDictionary><ResourceDictionary Source="\Dictionaries\ViewDictionary.xaml"></ResourceDictionary></ResourceDictionary.MergedDictionaries></ResourceDictionary></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="30"></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><ComboBox SelectionChanged="ComboBox_SelectionChanged" ItemsSource="{Binding sqlserverList}" Grid.Row="0" Grid.Column="0"></ComboBox><TreeView Name="tvMain" TreeViewItem.Expanded="tvMain_Expanded" Grid.Row="1" Grid.Column="0"><TreeView.ItemTemplate><HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource gli}}"><StackPanel Orientation="Horizontal"><TextBlock Text="{Binding Path=Name}"></TextBlock></StackPanel></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView><ContentControl x:Name="theContent" Grid.Row="1" Grid.Column="1" Content="{Binding Path=SelectedValue.Item, ElementName=tvMain}"></ContentControl></Grid></Window>

The lines that define the ResourceDictionaries have a blue squiggly line under them but when a compile happens that goes away but I still cannot edit the properties using the VS tools.

When I switch to the design window I can see an error:

Invalid URI: The format of the URI could not be determined.
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString, UriKind uriKind)
   at MS.Internal.Host.BinaryResourceImpl.get_FileUri()
   at MS.Internal.Host.MarkupProjectContext.GetBinaryResource(Uri uri)
   at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.TreeChangeListener.Microsoft.Windows.Design.DocumentModel.IDocumentTreeConsumer.HandleMessage(DocumentTreeCoordinator sender, MessageKey key, MessageArguments args)

TIA,

LS


Lloyd Sheen


images not showing up

$
0
0

this is my code, I cant see what's wrong maybe ye can shed some light

--------------------------------------------------------------------------(xaml)

                                        

<Window x:Class="ActorsObjDtPrvDtTmplt.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Stars and Starsigns" Height="250" Width="325"
        xmlns:local="clr-namespace:ActorsObjDtPrvDtTmplt">
    <Window.Resources>
        <Style x:Name="style1" TargetType="TextBlock">
            <Setter Property="FontSize" Value="16"/>
            <Setter Property="FontStyle" Value="Italic"/>
            <Setter Property="FontWeight" Value="Bold"/>            
        </Style>

        <ObjectDataProvider x:Key="cast" MethodName="Cast" ObjectType="{x:Type local:Agency}">
             <!--objectdataprovider.methodparameter-->
        </ObjectDataProvider>

        <DataTemplate x:Key="ActorTemplate" DataType="{x:Type local:Actor}">
            <StackPanel Orientation="Horizontal">
                <Image Width="60" Height="60" Source="{Binding Sign}"/>
                <!--style="{dynamic resource style1}-->
                <TextBlock Text="{Binding Name}"/>
                <TextBlock Text="{Binding DOB, StringFormat=d}" FontSize="13"/>
            </StackPanel>
        </DataTemplate>

    </Window.Resources>


    <!--calling the menu binding command-->
        <Window.CommandBindings>
            <!--customcommands=name of class, cmdactor=name of class inside the custom commands..envoking d command and calling d command-->
        <CommandBinding Command="local:CustomCommands.CmdAddActor" Executed="CmdAddActor_Executed" CanExecute="CmdAddActor_CanExecute" />
            <!--can execute? is an event, can be envoke or can dis work or wat?..which wire up with d commands..    -->
        </Window.CommandBindings>

    <!--calling the, key binding or mouse binding, making command-->
    <Window.InputBindings>
        <!-- Key="Control+1"-->
        <KeyBinding Command="local:CustomCommands.CmdAddActor" CommandParameter="1" Gesture="Ctrl+1"/>
        <KeyBinding Command="local:CustomCommands.CmdAddActor" CommandParameter="2" Gesture="Ctrl+2"/>        
    </Window.InputBindings>


    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="Add Actors">
                <!--get the 1 actor, call the command,  InputGestureText="Ctrl+1" (decoration to see that it's ctrl1/ctrl2-->
                <MenuItem Header="Add 1 Actor" Command="local:CustomCommands.CmdAddActor" CommandParameter="1" InputGestureText="Ctrl+1" />
                <!--get the 2 actor, call the command-->
                <MenuItem Header="Add 2 Actor"  Command="local:CustomCommands.CmdAddActor" CommandParameter="2"  InputGestureText="Ctrl+2" />
            </MenuItem>
        </Menu>
        <!--listbox display and getting it from the itemsource (cast) connection..-->
        <ListBox ItemsSource="{Binding Source={StaticResource cast}}" 
                 ItemTemplate="{StaticResource ActorTemplate}"/>
    </DockPanel>
</Window>

-------------------------------------------------------------------------------(xaml)

---------------------------------------------------------------------------(Actor.cs)

namespace ActorsObjDtPrvDtTmplt
{
    public class Actor
    {
        public string Name { get; set; }
        public DateTime DOB { get; set; }
        //public string StarSign { get; set; }
        public string Sign
        {
            get
            {
                if (DOB.Month < 6) return Environment.CurrentDirectory + "\\starsigns\\" + "capricorn.jpeg";
                else return Environment.CurrentDirectory + "\\starsigns\\" + "virgo.jpeg";
            }
        }
        //public override string ToString()
        //{
        //    return String.Format("{0} born {1}",Name, DOB);
        //}
    }   // end class
}

-------------------------------------------------------------------------------------(Actor.cs)

-------------------------------------------------------------------------------------(Agency.cs)

using System.Collections.ObjectModel;

namespace ActorsObjDtPrvDtTmplt
{
    static class Agency
    {
        //responsible for adding an actor
        public static ObservableCollection<Actor> _Cast; //public property called cast, list of actor, instead of list, use observableCollection,
                                                        //similarly to list,it do exact d same thing, but its useful for binding..
                                                        //_Cast is a collection of Actors..

        static Agency() //static constractor.. it starts wen d program start..it automatically starts wen dis program is started..
        {
            _Cast = new ObservableCollection<Actor>(); //creates new list
            //and it adds this 3 list name of actors..
            _Cast.Add(new Actor{ Name="Matt Damon", DOB=DateTime.Now});
            _Cast.Add(new Actor { Name = "Angelina Jolie", DOB = new DateTime(1990,1,12)});
            _Cast.Add(new Actor { Name = "Brad Pitt", DOB = DateTime.Now});

            //initializing of content
        }

        public static ObservableCollection<Actor> Cast() //Cast connection in xaml, it consumed in d listbox,
        {
            return _Cast;
        }


        //public static void AddAnctor(actor a)
        //_Cast.add(a);


        public static void AddActor(int noToAdd) //adding morgan freeman each time, wen it's pressed... it takes such a number of actor(morganfreeman)
        {
            for (int i = 0; i<noToAdd; i++)
            _Cast.Add(new Actor{Name="Morgan Freeman", DOB=new DateTime(1950,1,1)});
        }
    }   // end class
}

--------------------------------------------------------------------(Agency.cs)

--------------------------------------------------------------------(Code behind)

   

namespace ActorsObjDtPrvDtTmplt
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void CmdAddActor_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //MessageBox.Show("made it to CmdAddActor");
            //Agency.AddActor((int)e.Parameter);
            Agency.AddActor(Convert.ToInt32(e.Parameter)); //agency = collection class, addactor = a command to say to add an actor
        }

        private void CmdAddActor_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //disable, nothing here..
            if (Agency._Cast.Count < 5) e.CanExecute = true;
            else e.CanExecute = false;
        }
    }   // end class

    public static class CustomCommands
    {
        //command for the shortcuts
        public static RoutedCommand CmdAddActor = new RoutedCommand();
    }

}

--------------------------------------------------(code behind)

Error_1_The type or namespace name 'DateBinding' could not be found (are you missing a using directive or an assembly reference?)

$
0
0

my code works but im getting this error can someone explain what it means. Thanks in advance

------------------------------------------------------------(Xaml)

    

<Window x:Class="DateBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:loc="clr-namespace:DateBinding"
    Title="Window1" Height="450" Width="300">
    <Window.Resources>
        <loc:DateConverter x:Key="dteConverter"/>
        <loc:DateColorConverter x:Key="DteColConverter"/>
        <BooleanToVisibilityConverter x:Key="boolVisConverter"/>
        <loc:Txt2LenConverter x:Key="txt2lenConverter"/>
        <loc:DayWeekToOpacityConverter x:Key="dwToOpacityConverter"/>
    </Window.Resources>

    <StackPanel>
        <Slider Name="slDate" Maximum="20" SmallChange="1" Margin="3"/>
        <TextBox  Name="txtDate" VerticalAlignment="Top" FontSize="28" Margin="3" Padding="3,0,0,0" Background="{Binding Text, Converter={StaticResource DteColConverter}, ElementName=txtDate, Mode=OneWay}">
            <TextBox.Text>
                <Binding ElementName="slDate" Path="Value" Mode="OneWay" Converter="{StaticResource dteConverter}"/>
            </TextBox.Text>
        </TextBox>
        <CheckBox Name="chkPicture" Content="Check for Photo" IsChecked="True"/>
        <Image Source="Penguins.jpg" Visibility="{Binding ElementName=chkPicture, Path=IsChecked, Converter={StaticResource boolVisConverter}}" 
               Opacity="{Binding Text, ElementName=txtDate, Converter={StaticResource dwToOpacityConverter}}"/>
        <TextBox Name="txtLen" FontSize="30" Text="Initial"/>
        <ProgressBar Height="10" Value="{Binding ElementName=txtLen, Path=Text, Converter={StaticResource txt2lenConverter}}"/>
    </StackPanel>
</Window>

--------------------------------------------------------------(xaml)

-----------------------------------------------------------------(code behind)

namespace DateBinding
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
}

------------------------------------------------------------(code behind)

-----------------------------------------------------------(date converter)

namespace DateBinding
{
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime d = DateTime.Now;
            d = d.AddDays((Double)value);
            return d.ToShortDateString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }   // end DateConverter

    public class DateColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime d;
            if (!DateTime.TryParse((string)value, out d))

                //return new SolidColorBrush(Colors.WhiteSmoke);
                //return new SolidColorBrush(Color.FromArgb(255, 255, 255, 0));
                return new SolidColorBrush(Colors.Wheat);
            if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                return new SolidColorBrush(Color.FromArgb(255, 155, 0, 55));
            return new SolidColorBrush(Colors.Aquamarine);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class Txt2LenConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = (string)value;
            return str.Length * 2;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class DayWeekToOpacityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime d;
            DateTime.TryParse((string)value, out d);
            return (float)d.DayOfWeek / 10;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

-------------------------------------------------------------(dateConverter)

WPF ResourceDictionaries - Merging at runtime to create different application configurations?

$
0
0

I have an application that will have numerous configurations (also can be thought of as a plugin model) - all based on a baseline configuration. So my baseline configuration's Views and ViewModels are location in a root folder inside my project with a Resources.xaml. Inside this baseline XAML file I have all DataTemplates for my baseline product.

Now my thought is that I can create customized configurations or customized offshoots of my main product by using product specific resource files in which I'll be able to specify customized views, customized view models, etc. I think this is a good way of setting this up.

The problem: The problem is that my customized .xaml resource files don't seem to merge theDataTemplates specified inside of them into the main resource dictionary. So when I try and load a customized configuration, my baseline views render fine but my customized ones [specified in my product specific resource file] can't see to template mappings to render views in the application. What am I doing wrong here?

ResourceDictionary productDictionary = Application.LoadComponent(new Uri("CustomUI;component/" + vce.ResourcePath, UriKind.Relative)) as ResourceDictionary;
ResourceDictionary sharedDictionary = Application.LoadComponent(new Uri("CustomUI;component/Shared/View/BaselineResources.xaml", UriKind.Relative)) as ResourceDictionary;

Application.Current.Resources.MergedDictionaries.Add(productDictionary);
Application.Current.Resources.MergedDictionaries.Add(sharedDictionary);

In XAML, how do you use a namespace prefix in a property element syntax?

$
0
0

Hello,

I need to use a PasswordBox in MVVM, but since PasswordBox's Password property isn't a dependency property, and can't be bound to a property in the ViewModel, I went searching and found a nice attached property (by Pete O'Hanlon).  I was easily able to get it to work, by adding an attribute to the <PasswordBox> element:

<PasswordBox
	Lib:BoundPasswordBox.BoundPassword="{Binding Path=Password, UpdateSourceTrigger=PropertyChanged}"
	...

Next, I need to add validation, so I tried turning it into a property element instead, but I can't figure out the syntax for the namespace prefix (Lib:):

<PasswordBox
	... ><PasswordBox.Lib:BoundPasswordBox.BoundPassword><Binding
			Path="Password"
			UpdateSourceTrigger="PropertyChanged"><Binding.ValidationRules>
...

So, what's the syntax for an attached property with a namespace prefix in a property element?

Thanks


Uncaged

Exception when printing XPS-Document

$
0
0

Hallo,

with our application document will be printed via the XpsDocumentWriter.

Almost everytime the print works without any problems.

But from time to time the following error occurs:

PrintTicket provider failed to convert DEVMODE to PrintTicket.Win32 error:-2147467259
   at MS.Internal.Printing.Configuration.PTProvider.ConvertDevModeToPrintTicket(Byte[] devMode,PrintTicketScope scope)
   at System.Printing.Interop.PrintTicketConverter.InternalConvertDevModeToPrintTicket(PTProviderBase provider,Byte[] devMode,PrintTicketScope scope)
   at System.Printing.PrintTicketManager.ConvertDevModeToPrintTicket(Byte[] devMode)
   at System.Printing.PrintQueue.get_UserPrintTicket()
   at System.Windows.Xps.Serialization.NgcPrintTicketManager.ConstructPrintTicketTree(XpsSerializationPrintTicketRequiredEventArgs args)
   at System.Windows.Xps.Serialization.NgcSerializationManagerAsync.OnNGCSerializationPrintTicketRequired(Object operationState)
   at System.Windows.Xps.Serialization.NgcSerializationManagerAsync.SaveAsXaml(Object serializedObject)
   at System.Windows.Xps.XpsDocumentWriter.WriteAsync(DocumentPaginator documentPaginator,PrintTicket printTicket)
   at Willis.Base.Pdf.PagePrintMailControl.simpleButtonPrint_Click(Object sender,EventArgs e)

What could be the reason for this?

Printing one document on day a on the same printer by the same user can result in the error but on day b the same document on the same printer by the same user can be printed without an error, what is pretty strange.

Thanks for your help.

Converting WinForms to WPF - Unbound Datagrid?

$
0
0

Originally posted in VB, was told it would be better asked here...

Due to a previous issue I had where the Designer lost most of my WinForms design, since I'm rebuilding my forms for this program from scratch anyway I decided to make the jump to the 2010's and convert to WPF. Most of my vbcode was intact and I was able to copy to the new project with relative ease once I figured out a couple differences like .Enabled -> .IsEnabled and .Text -> .Content, and figured out how to replace the Timers with DispatcherTimers among some other things... I'm sure as I go through updates and other changes I'll slowly get things more streamlined with newer items available in .net4/WPF.

The one thing I haven't been able to figure out is how to work with an unbound DataGrid. I have columns manually added in the XAML designer, but adding, removing and reading Rows from the VB side has me baffled. ".Rows" doesn't appear to be a member of DataGrid as it was with DGVs, and no other member I can find has an Add function. I've also come up empty looking in the help for DataGrids on MSDN's documentation, and any other sites I find either deals directly with bound data grids or use other members I can't find like "RowsHierarchy"... 

My DataGrid has 4 columns as follows:
TextBox column: Path & File Name of a sound file, Hidden
TextBox column: File Name only, Visible
TextBox column: Length of a sound file in seconds, Hidden
TextBox column: Formatted "time" of sound file (m:ss), Visible

Some of the actions I'm trying to perform with this DataGrid are as follows:

    Private Sub FileAdd(Filename As String)
            'Code
            DataGridView1.Rows.Add(Filename, IO.Path.GetFileNameWithoutExtension(Filename), dxListPlay.Duration, TimeSpan.FromSeconds(Math.Round(dxListPlay.Duration, 0)))
            'More Code
    End Sub

    Private Sub tottimecalc()
        Dim total As Double = 0
        For Each r As DataGridViewRow In DataGridView1.Rows
            Dim cellvalue As Double
            If Double.TryParse(CStr(r.Cells(2).Value), cellvalue) Then total += cellvalue
        Next
            'More Code
    End Sub

    Private Sub MoveRow(ByVal i As Integer)
            If (DataGridView1.SelectedCells.Count > 0) Then
                Dim curr_index As Integer = DataGridView1.CurrentCell.RowIndex
                Dim curr_col_index As Integer = DataGridView1.CurrentCell.ColumnIndex
                Dim curr_row As DataGridViewRow = DataGridView1.CurrentRow
                DataGridView1.Rows.Remove(curr_row)
                DataGridView1.Rows.Insert(curr_index + i, curr_row)
                DataGridView1.CurrentCell = DataGridView1(curr_col_index, curr_index + i)
            End If
    End Sub

    Private Sub btn_RemList_Click(sender As System.Object, e As System.EventArgs) Handles btn_RemList.Click
            If (DataGridView1.SelectedCells.Count > 0) Then
                DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
            End If
    End Sub

    Private Sub btn_ClearList_Click(sender As System.Object, e As System.EventArgs) Handles btn_ClearList.Click
        DataGridView1.Rows.Clear()
    End Sub

    Private Sub btn_PlayList_Click(sender As System.Object, e As System.EventArgs) Handles btn_PlayList.Click
        If DataGridView1.Rows.Count > 0 Then
            lbl_NowPlaying.Text = DataGridView1.Rows(0).Cells(1).Value
            dxListPlay = New Audio(DataGridView1.Rows(0).Cells(0).Value)
            'Other Code
        End If
    End Sub

Any help on getting this resolved would be appreciated. This is the only thing standing in the way of a working program again that I can get back to improving instead of just trying to get to a point where I can even edit it in the first place. (I know I've sucked at nominating/marking answers in the past, I promise I'll be better but you've gotta give me time to test answers.) 

visual studio/blend and mvvm

$
0
0

hello,

i been working with wpf and mvvm for a while now.

up until now i created the view model class and in the code behind of the window i wrote:

this.DataContext= m_mainPageVM;

and it all worked fine, however if i want to make my life easier, for example by setting a data binding through visual studio properties panel i cant find my vm there,
so i have to write the binding text manually.

so i tried adding a Data source through the visual studio DataSource panel, in there i can find the Vm class but when i try to bind something to it, it just dosen't work...

so i guess what i'm asking is:
what is the best way to work with the designer and mvvm?

thank you very much in advance

jony.

Dependency Property Choices From XAML Instead of Enum

$
0
0

I have a custom CheckBox UserControl which displays differently depending on the dependency property "CheckBoxStyle".  This DP is based on an enumeration:

Public Enum Styles
    valve_circle
    electrical_switch
    valve_line
    heater_coil
    ios_switch
    plunger_switch
    double_throw_switch
    carousel
End Enum

In my resources in an XAML, there is a separate style for each of the above items.  All is working great.  The only issue is that  when I add a new type of checkbox, I need to code it in my "Custom Controls" project, then take the xaml file AND the code-behind file and copy them to other projects to implement.  I know this is a common situation.  The only reason I need to change the code-behind file is to add the new style to the enumeration.

Here's the question:  Is it possible to base the DP in code-behind on a list of styles contained in the XAML instead of on an enumeration?  This would enable me to only need to copy the XAML file to other projects, rather than XAML and code-behind files.

If the answer is NO, is there a way instead to modify the enumeration using reflection, so I could create it each time the project is loaded?  Would that be a cumbersome fix?  Am I making a big deal over nothing?

Thanks...


Ron Mittelman

Collection View Source-- Add image to the header

$
0
0

XAML<Window x:Class="cvsFormulaOne.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dat="clr-namespace:System.Windows.Data;assembly=PresentationFramework" xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" xmlns:local="clr-namespace:cvsFormulaOne" Title="MainWindow" Height="350" Width="600" Loaded="Window_Loaded"><Window.Resources><DataTemplate x:Key="hdrTemplate"><StackPanel><TextBlock Text="{Binding Path=Name}" Margin="0,5" FontSize="22" FontStyle="Italic"><TextBlock.Background><RadialGradientBrush><GradientStop Color="Black" Offset="0" /><GradientStop Color="#47E5D9D9" Offset="0.729" /></RadialGradientBrush></TextBlock.Background></TextBlock></StackPanel></DataTemplate><local:F1DB x:Key="f1DB"/><ObjectDataProvider x:Key="odpF1" ObjectType="{x:Type local:F1DB}" MethodName="getTeams"></ObjectDataProvider><CollectionViewSource x:Key="cvsF1" Source="{Binding Source={StaticResource odpF1}}"><CollectionViewSource.SortDescriptions><scm:SortDescription PropertyName="noChampionships" Direction="Ascending"/></CollectionViewSource.SortDescriptions><CollectionViewSource.GroupDescriptions><dat:PropertyGroupDescription PropertyName="EngineMaker"/> </CollectionViewSource.GroupDescriptions></CollectionViewSource></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="*"></RowDefinition><RowDefinition Height="3*"></RowDefinition></Grid.RowDefinitions><StackPanel Orientation="Horizontal"><Border Margin="5,5"><StackPanel><Label>No of Driver Championship</Label><StackPanel><RadioButton GroupName="rbgNoChamp" Click="RadioButton_Click"

Tag="ASC" IsChecked="true">Ascending</RadioButton><RadioButton GroupName="rbgNoChamp"

Click="RadioButton_Click" Tag="DESC">Descending</RadioButton></StackPanel></StackPanel><Border.Background><RadialGradientBrush><GradientStop Color="Black" Offset="0" /><GradientStop Color="#47E5D9D9" Offset="0.729" /></RadialGradientBrush></Border.Background></Border><Border Margin="5,5" MinWidth="80"><StackPanel><CheckBox HorizontalAlignment="Center" Margin="0,5" Name="chkMakerFilter"
Checked="chkMakerFilter_Checked" Unchecked="chkMakerFilter_Unchecked">Filter</CheckBox>

<ComboBox Name="cbxMaker" VerticalAlignment="Top"
HorizontalAlignment="Stretch" Margin="5,0"
SelectionChanged="cbxMaker_SelectionChanged" IsEnabled="False"></ComboBox></StackPanel><Border.Background x:Uid="hi"><LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"><GradientStop Color="Black" Offset="0" /><GradientStop Color="#47E5D9D9" Offset="0.729" /></LinearGradientBrush></Border.Background></Border><Border Margin="5,5" MinWidth="80"><StackPanel><CheckBox HorizontalAlignment="Center" Margin="0,5" Name="chkTeamNameTxtFilter"
Checked="chktxtTeamNameFilter_Checked"
Unchecked="chktxtTeamNameFilter_Unchecked">Filter</CheckBox><TextBox Name="txtTeamNameFilter" VerticalAlignment="Top"
MinWidth="50" HorizontalContentAlignment="Center"
HorizontalAlignment="Stretch" Margin="5,0"
TextChanged="txtTeamNameFilter_TextChanged" IsEnabled="False"></TextBox></StackPanel><Border.Background><LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"><GradientStop Color="Black" Offset="0" /><GradientStop Color="#47E5D9D9" Offset="0.729" /></LinearGradientBrush></Border.Background></Border><Border Margin="5,5" MinWidth="80"><StackPanel><CheckBox HorizontalAlignment="Center" Margin="0,5" Name="chkGroupFilter"
Checked="chkGroupFilter_Checked" Unchecked="chkGroupFilter_Unchecked"
Content="Group by No Constructors"></CheckBox><CheckBox HorizontalAlignment="Center" Margin="5"
Name="chkGroupMakerFilter" Checked="chkGroupMakerFilter_Checked"
Unchecked="chkGroupMakerFilter_Unchecked" Content="Group by Teams"></CheckBox></StackPanel><Border.Background><LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"><GradientStop Color="Black" Offset="0" /><GradientStop Color="#47E5D9D9" Offset="0.729" /></LinearGradientBrush></Border.Background></Border></StackPanel><Border Background="Red" CornerRadius="8" Grid.Row="1"><ListBox Name="lbxData" Margin="5" ItemsSource="{Binding Source={StaticResource cvsF1}}"><ListBox.GroupStyle><GroupStyle HeaderTemplate="{StaticResource hdrTemplate}"/></ListBox.GroupStyle></ListBox></Border></Grid></Window>

XAML.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.ComponentModel;

namespace cvsFormulaOne
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        CollectionViewSource cvs;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // retrieve CollectionViewSource resource from XAML
            cvs = this.Resources["cvsF1"] as CollectionViewSource;
            // fill combobox with EngineMakers of F1Teams
            cbxMaker.ItemsSource = Enum.GetNames(typeof(Makers));
            // set first Maker as selected if >0 Makers
            if (cbxMaker.Items.Count > 0) cbxMaker.SelectedIndex = 0;
            cvs.Filter += new FilterEventHandler(cvs_Filter);
        }

        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            // retrieve the CollectionViewSource from the resources section of XAML
            string sortOrder = ((RadioButton)sender).Tag as String;         // query Radiobutton for sort order
            cvs.SortDescriptions.Clear();           // clear out existing sorting

            // apply new sort order
            if (sortOrder == "ASC") cvs.SortDescriptions.Add(new SortDescription("noDriverChampionships", 
ListSortDirection.Ascending)); else cvs.SortDescriptions.Add(new SortDescription("noDriverChampionships",
ListSortDirection.Descending)); } void cvs_Filter(object sender, FilterEventArgs e) { F1Team f1 = e.Item as F1Team; if (chkMakerFilter.IsChecked == true) { //Makers m = (Makers)cbxMaker.SelectedItem; Makers m = (Makers)Enum.Parse(typeof(Makers), cbxMaker.SelectedItem.ToString(), true); if (f1.EngineMaker == m) e.Accepted = true; else e.Accepted = false; } else if (chkTeamNameTxtFilter.IsChecked == true) { if (f1.TeamName.ToLower().StartsWith(txtTeamNameFilter.Text.ToLower())) e.Accepted = true; else e.Accepted = false; } } private void cbxMaker_SelectionChanged(object sender, SelectionChangedEventArgs e) { cvs.View.Refresh(); chkTeamNameTxtFilter.IsChecked = false; } private void txtTeamNameFilter_TextChanged(object sender, TextChangedEventArgs e) { cvs.View.Refresh(); } private void chkTeamNameTxtFilter_Checked(object sender, RoutedEventArgs e) { txtTeamNameFilter.IsEnabled = true; chkMakerFilter.IsChecked = false; chkGroupFilter.IsChecked = false; txtTeamNameFilter.Focus(); cvs.View.Refresh(); } private void chkTeamNameTxtFilter_Unchecked(object sender, RoutedEventArgs e) { txtTeamNameFilter.IsEnabled = false; } private void chkGroupMakerFilter_Checked(object sender, RoutedEventArgs e) { chkTeamNameTxtFilter.IsChecked = false; chkMakerFilter.IsChecked = false; chkGroupFilter.IsChecked = false; cvs.GroupDescriptions.Clear(); cvs.SortDescriptions.Clear(); cvs.SortDescriptions.Add(new SortDescription("TeamName", ListSortDirection.Ascending)); cvs.SortDescriptions.Add(new SortDescription("noDriverChampionships", ListSortDirection.Descending)); cvs.GroupDescriptions.Add(new PropertyGroupDescription("EngineMaker")); } private void chkGroupMakerFilter_Unchecked(object sender, RoutedEventArgs e) { cvs.GroupDescriptions.Clear(); cvs.SortDescriptions.Clear(); cvs.View.Refresh(); } private void chkGroupFilter_Unchecked(object sender, RoutedEventArgs e) { cvs.GroupDescriptions.Clear(); cvs.SortDescriptions.Clear(); cvs.View.Refresh(); } private void chkGroupFilter_Checked(object sender, RoutedEventArgs e) { chkTeamNameTxtFilter.IsChecked = false; chkMakerFilter.IsChecked = false; cvs.GroupDescriptions.Clear(); cvs.SortDescriptions.Clear(); cvs.SortDescriptions.Add(new SortDescription("noChampionships", ListSortDirection.Ascending)); cvs.SortDescriptions.Add(new SortDescription("noDriverChampionships", ListSortDirection.Ascending)); noChampionships pogc = new noChampionships(); cvs.GroupDescriptions.Add(new PropertyGroupDescription("noChampionships", new noChampionships())); } private void chkMakerFilter_Checked(object sender, RoutedEventArgs e) { cbxMaker.IsEnabled = true; this.chkTeamNameTxtFilter.IsChecked = false; chkGroupFilter.IsChecked = false; cvs.View.Refresh(); } private void chkMakerFilter_Unchecked(object sender, RoutedEventArgs e) { cbxMaker.IsEnabled = false; this.chkTeamNameTxtFilter.IsChecked = true; cvs.View.Refresh(); } private void chktxtTeamNameFilter_Checked(object sender, RoutedEventArgs e) { txtTeamNameFilter.IsEnabled = true; chkMakerFilter.IsChecked = false; chkGroupFilter.IsChecked = false; txtTeamNameFilter.Focus(); cvs.View.Refresh(); } private void chktxtTeamNameFilter_Unchecked(object sender, RoutedEventArgs e) { txtTeamNameFilter.IsEnabled = false; } } }
    class noChampionships : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo 
culture) { // establish range of values and assign incoming value to one of three divisions int minPrev, maxPrev, thirdInterval, inValue; int[] ranges = F1DB.getRangenoChampionships(); inValue = (int)value; minPrev = ranges[0]; maxPrev = ranges[1]; thirdInterval = (maxPrev - minPrev) / 3; if (inValue < thirdInterval) return string.Format("{0}-{1}", minPrev, minPrev + thirdInterval); if (inValue < thirdInterval * 2) return string.Format("{0}-{1}", minPrev + thirdInterval,
minPrev + thirdInterval * 2); return String.Format("{0}-{1}", minPrev + thirdInterval * 2, maxPrev); } public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
CLASSES

    class noChampionships : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
System.Globalization.CultureInfo culture) { // establish range of values and assign incoming value to one of three divisions int minPrev, maxPrev, thirdInterval, inValue; int[] ranges = F1DB.getRangenoChampionships(); inValue = (int)value; minPrev = ranges[0]; maxPrev = ranges[1]; thirdInterval = (maxPrev - minPrev) / 3; if (inValue < thirdInterval) return string.Format("{0}-{1}", minPrev, minPrev + thirdInterval); if (inValue < thirdInterval * 2) return string.Format("{0}-{1}", minPrev + thirdInterval, minPrev +
thirdInterval * 2); return String.Format("{0}-{1}", minPrev + thirdInterval * 2, maxPrev); } public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cvsFormulaOne { public enum Makers { Toyota, Ford, Jaguar, Mercedes, Renualt, Lotus }; public class F1Team { public Makers EngineMaker { get; set; } public string TeamName { get; set; } public int noDriverChampionships { get; set; } public int noChampionships { get; set; } public override string ToString() { return String.Format("{0} Engine \t{1} \t(Won {2} Driver and Won {3} Constructor Champioships).",
EngineMaker, TeamName, noDriverChampionships, noChampionships); } } // end class } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace cvsFormulaOne { public class F1DB { private static ObservableCollection<F1Team> F1Teams = new ObservableCollection<F1Team>(); public static ObservableCollection<F1Team> getTeams() { return F1Teams; } static F1DB() { // populate with some F1Teams objects F1Teams.Add(new F1Team { EngineMaker = Makers.Toyota, TeamName = "Toyota F1",
noDriverChampionships = 0, noChampionships = 0}); F1Teams.Add(new F1Team { EngineMaker = Makers.Ford, TeamName = "Steward F1",
noDriverChampionships = 0, noChampionships = 0 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Jaguar, TeamName = "Jaguar F1",
noDriverChampionships = 0, noChampionships = 0 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Mercedes, TeamName = "Vodafone McLaren",
noDriverChampionships = 12, noChampionships = 8 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Mercedes, TeamName = "Mercedes F1",
noDriverChampionships = 2, noChampionships = 0 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Mercedes, TeamName = "Force India",
noDriverChampionships = 0, noChampionships = 0 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Renualt, TeamName = "Red Bull Racing",
noDriverChampionships = 3, noChampionships = 3 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Renualt, TeamName = "Williams F1",
noDriverChampionships = 5, noChampionships = 5 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Renualt, TeamName = "Caterham F1",
noDriverChampionships = 0, noChampionships = 0 }); F1Teams.Add(new F1Team { EngineMaker = Makers.Lotus, TeamName = "Lotus F1",
noDriverChampionships = 2, noChampionships = 2 }); } // Adds another F1Teams to database public static void addCar(F1Team F1) { F1Teams.Add(F1); } public static int[] getRangenoChampionships() { // return min and max of values in db for noChampionships return new int[] { (from F1 in F1Teams select F1.noChampionships).Min(), (from F1 in F1Teams select F1.noChampionships).Max() }; } } // end class }
And what I'd like to know how would u put an image into the header example the manufacturer icon. Can anyone help me, cheers.

NB:Anyone who might create this file, and you'll see the ui, I know its a bit odd of a UI, but sorry, not good at create stylish the UI

How to get The Modified date of image ??

$
0
0

Hello All,

                I am trying to get the Modified  date of a  image using c# like in Mozilla FireFox. I getting some other property's but not getting this  is Any option to get this .

with regards ,

jophy .


WPF datagrid filter doesn't work dosen't work

$
0
0

Greetings,

I'm trying to have a WPF data grid results filtered and I can't get it to work.  The filter event never fires and all the rows remain.

   <DockPanel.Resources>
                                  
                                           
     <CollectionViewSource x:Key="DetailsCollection"
                           Filter="PriceDetailsFilter"
                           Source="{Binding Path=PriceChangeDetails,
                           UpdateSourceTrigger=PropertyChanged}" >
     </CollectionViewSource>
                                          
    </DockPanel.Resources>
                                     
                                           
  <wpf:DataGrid  CanUserSortColumns="True" CanUserAddRows="False" IsReadOnly="False"
      Block.TextAlignment="Left"
      ItemsSource="{Binding Source={StaticResource DetailsCollection},
   UpdateSourceTrigger=PropertyChanged}"> 

    public void PriceDetailsFilter(object sender, FilterEventArgs e)        {            e.Accepted = false; // breakpoint never hits                    }

  Does anyone see what I'm doing wrong?

Thanks,

                                                                                                      

Drag and drop between 2 listboxes, COMException

$
0
0

Hi,

This problem occurs every now and then when I drag one element from ListBox to the other listbox. "Error HRESULT E_FAIL has been returned from a call to a COM component." COMException is thrown when I call "DragDrop.DoDragDrop". The code below shows how and where exactly I call DoDragDrop.

object[] parameters = { source, data }; Dispatcher.CurrentDispatcher.BeginInvoke(

new Action(() => DoDragDrop(parameters))

, System.Windows.Threading.DispatcherPriority.Background, null);

where DoDragDrop(parameters) is: public static void DoDragDrop(params object[] list) { //try //{ DragDrop.DoDragDrop(list[0] as DependencyObject, list[1], DragDropEffects.Move); //} //catch //{ //} }


I've read about similar problems being resolved by doing the drag and drop asynchronously hence the Dispatcher call. Still the problem persists. Catching all the exceptions helps - it works properly from what I can notice - which suggests that the exception doesn't break the drag and drop operation. I would prefer to know and eliminate the cause. I'd appreciate any help.

Best regards,

Simon



Confusing Question About MVVM and Window Closing Event (Setting Cancel to True Works Once)

$
0
0

Strictly adhering to MVVM, I'd like to cancel the closing of a window when the user clicks the "X" or standard Windows close button.

The ViewModel is as follows:

private RelayCommand<CancelEventArgs> _windowClose = null;
public RelayCommand<CancelEventArgs> WindowClose {
	get {
		if (_windowClose == null) {
			_windowClose = new RelayCommand<CancelEventArgs>(
				(args) => {
					args.Cancel = true;
					BeforeExitViewModel tmp = new BeforeExitViewModel();
					WindowManager.ShowWindow(tmp);
				}, (args) => { return (true); });
		}
		return (_windowClose);
	}
}

I pop-up a quick and dirty ViewModel so the user can save changes if they are dirty or cancel the closing event (keep their work open). From the view:

<i:Interaction.Triggers><i:EventTrigger EventName="Closing"><nvis:EventToCommand Command="{Binding WindowClose}" /></i:EventTrigger></i:Interaction.Triggers>

I'm new-ish to MVVM so this really seems correct and simple to me. Trouble is, it works... ONCE!  If the user clicks "Close" then cancels, the window view remains open until they click a second time. Although the RelayCommand DOES fire, it seems setting e.Cancel to true has NO EFFECT.  Why is this?

I know there are workarounds and I can use code behind, but I wanted to post on here to learn from this issue.  Thank you in advance for any helpful replies I get!

Make datetime field format as per the regional setting of the machine. WPF (MVVM)

$
0
0

Hi,

I have a datetime field in WPF(MVVM). and it is binded to a text box.

I want to put the string formt of the text box as per the format of the current system regional settting. Can you please help, how to achieve this?

Thanks, Sai


Nested DataGrid with inner datagrid in rowdetails template

$
0
0

Hi,

I am using nested datagrid with inner datagrid in my rowdetailstemplate. I am able to get functionality of tree structure using nested grid. Inner datagrid has multiple rows with one of the column as textbox defined inside <DataGridTemplateColumn.CellTemplate>. This textbox has lostfocus event which is firing properly.

Problem is when inner datagrid is expanded and textbox control is changed on 3rd row. I am not able to get correct value of innergrid.selectedIndex property (correct value should be 2) it is always zero.

Help required thanks in advance



Multiple level treeview

$
0
0

Hi all,

I want a treeview with several level, but each time a different number of level.

I do : 

In xaml : 

<TreeView Name="TreeViewTask" ItemsSource="{Binding}" DataContext="{Binding}"><TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Value}">

<TextBlock FontWeight="Bold" Text="{Binding Path=Key}" />

<HierarchicalDataTemplate.ItemTemplate><DataTemplate><TextBlock Text="{Binding}"/></DataTemplate></HierarchicalDataTemplate.ItemTemplate></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

And the code behind : 

TreeViewTask.DataContext = currentProg.Tests;

Where Tests is a dictionary of string / Object

Is it possible to make a treeview with several level in this way? (I don't know the number of level)

Thanks for your help !

TextBox in TreeViewItem LostFocus event

$
0
0

I have a textbox inside the TreeViewItem.  The textbox doesn't lose focus when selecting another item in the treeview or in the application.  The user can select a TreeViewItem, which enables focus on the Textbox, and then select another TreeViewItem, which will also enable focus on the second TextBox.  The expected results should be the TextBox is only focused when the user manually clicks on the TreeViewItem.

Is there a way to force the textbox to lose focus in a TreeViewItem?

WPF app with resize property will crash in Windows 8 OS (0x88980406 )

$
0
0

Dear All

Can you help to analysis this issue?

WPF app with resize property will crash in Windows 8 OS (0x88980406 )

<<Reproduce Step >>

  1. Create a Dialog based WPF application with VS2010.
  2. Mainwindow.xaml <Window> section ResizeMode property with the value of “CanResizeWithGrip or CanResize or CanMinimize”. Set as “NoResize” value will be OK.
  3. Mouse move focus to some control, such as check box/list box etc.
  4. Press Win+D to minimize the dialog UI.
  5. Press Win+D again to restore the dialog UI to desktop. Then the abnormal will be occurred.

<<Coding>>

<Window x:Class="WPF_ResizeMode_Abnormal.MainWindow" ResizeMode="CanResizeWithGrip" ></Window>

<<Notes>>

  1. This issue cannot be reproduced on Windows7 OS.
  2. This issue cannot be reproduced, if ResizeMode property with value NoResize.
  3. This issue can be reproduced with or without ZDP and latest patch files.
  4. This issue can be reproduced on most of TOSHBIA PCs, NOT all the PCs. If one PC can be reproduced once, it can be reproduced every time.
  5. There are many discussion for the HRESULT error code 0x88980406 without solution.
    1. http://connect.microsoft.com/VisualStudio/feedback/details/500410/wpf-crashes-with-error-hresult-0x88980406
    2. http://connect.microsoft.com/VisualStudio/feedback/details/674249/wpf-renderer-thread-exited-with-codes-0x88980406-0x88980403


Guo


maximize window wpf

$
0
0

I have a window with the following properties:

ShowInTaskbar="False"WindowStyle="None"ResizeMode="NoResize"Topmost="True"AllowsTransparency="True"Background="Transparent"

and I want to maximize the window after pressing a button with the following line:

this.WindowState=System.Windows.WindowState.Maximized;

in doing so, the window is positioned me in the upper left but it is not maximized.

also tested with the following lines but did not work:

this.Height=SystemParameters.MaximizedPrimaryScreenHeight;this.Width=SystemParameters.MaximizedPrimaryScreenWidth;this.Top=0;this.Left=0;

Anyone know how to solve it?

Thank you very much.

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>