Search Results

Search found 108 results on 5 pages for 'dependencyobject'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Silverlight Chat WrapPanel Crash / Bug

    - by Matt
    I've been given the task to create a simple Silverlight chat box for two people. My control must adhere to the following requirements Scrollable Text must wrap if it's too long When a new item / message is added it must scroll that item into view Now I've successfully made a usercontrol to meet these requirements, but I've run into a possible bug / crash that I can't for the life of me fix. I'm looking for either a fix to the bug, or a different approach to creating a scrollable chat control. Here's the code I've been using. We'll start with my XAML for the chat window <ListBox x:Name="lbChatHistory" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled" > <ListBox.ItemTemplate> <DataTemplate> <Grid Background="Beige"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70"></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock x:Name="lblPlayer" Foreground="{Binding ForeColor}" Text="{Binding Player}" Grid.Column="0"></TextBlock> <ContentPresenter Grid.Column="1" Width="200" Content="{Binding Message}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> The idea is to add a new Item to the listbox. The Item (as layed out in the XAML) is a simple 2 column grid. One column for the username, and one column for the message. Now the "items" that I add to the ListBox is a custom class. It has three properties (Player, ForeColor, and Message) that I using binding on within my XAML Player is a string of the current user to display. ForeColor is just a foreground color preference. It helps distinguish the difference between messages. Message is a WrapPanel. I programmatically break the supplied string on the white space for each word. Then for each word, I add a new TextBlock element to the WrapPanel Here is the custom class. public class ChatMessage :DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static DependencyProperty PlayerProperty = DependencyProperty.Register( "Player", typeof( string ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnPlayerPropertyChanged ) ) ); public static DependencyProperty MessageProperty = DependencyProperty.Register( "Message", typeof( WrapPanel ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnMessagePropertyChanged ) ) ); public static DependencyProperty ForeColorProperty = DependencyProperty.Register( "ForeColor", typeof( SolidColorBrush ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnForeColorPropertyChanged ) ) ); private static void OnForeColorPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.ForeColor = ( SolidColorBrush ) e.NewValue; } public ChatMessage() { Message = new WrapPanel(); ForeColor = new SolidColorBrush( Colors.White ); } private static void OnMessagePropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.Message = ( WrapPanel ) e.NewValue; } private static void OnPlayerPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.Player = e.NewValue.ToString(); } public SolidColorBrush ForeColor { get { return ( SolidColorBrush ) GetValue( ForeColorProperty ); } set { SetValue( ForeColorProperty, value ); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs( "ForeColor" )); } } public string Player { get { return ( string ) GetValue( PlayerProperty ); } set { SetValue( PlayerProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "Player" ) ); } } public WrapPanel Message { get { return ( WrapPanel ) GetValue( MessageProperty ); } set { SetValue( MessageProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "Message" ) ); } } } Lastly I add my items to the ListBox. Here's the simple method. It takes the above ChatMessage class as a parameter public void AddChatItem( ChatMessage msg ) { lbChatHistory.Items.Add( msg ); lbChatHistory.ScrollIntoView( msg ); } Now I've tested this and it all works. The problem I'm getting is when I use the scroll bar. You can scroll down using the side scroll bar or arrow keys, but when you scroll up Silverlight crashes. FireBug returns a ManagedRuntimeError #4004 with a XamlParseException. I'm soo close to having this control work, I can taste it! Any thoughts on what I should do or change? Is there a better approach than the one I've taken? Thanks in advance. UPDATE I've found an alternative solution using a ScrollViewer and an ItemsControl instead of a ListBox control. For the most part it's stable.

    Read the article

  • WPF - Random hanging with file browser attached behaviour.

    - by Stimul8d
    Hi, I have an attached behavior defined thusly,.. public static class FileBrowserBehaviour { public static bool GetBrowsesOnClick(DependencyObject obj) { return (bool)obj.GetValue(BrowsesOnClickProperty); } public static void SetBrowsesOnClick(DependencyObject obj, bool value) { obj.SetValue(BrowsesOnClickProperty, value); } // Using a DependencyProperty as the backing store for BrowsesOnClick. This enables animation, styling, binding, etc... public static readonly DependencyProperty BrowsesOnClickProperty = DependencyProperty.RegisterAttached("BrowsesOnClick", typeof(bool), typeof(FileBrowserBehaviour), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(BrowsesOnClickChanged))); public static void BrowsesOnClickChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { FrameworkElement fe = obj as FrameworkElement; if ((bool)args.NewValue) { fe.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(OpenFileBrowser); } else { fe.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(OpenFileBrowser); } } static void OpenFileBrowser(object sender, MouseButtonEventArgs e) { var tb = sender as TextBox; if (tb.Text.Length < 1 || tb.Text=="Click to browse..") { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Executables | *.exe"; if (ofd.ShowDialog() == true) { Debug.WriteLine("Setting textbox text-" + ofd.FileName); tb.Text = ofd.FileName; Debug.WriteLine("Set textbox text"); } } } } It's a nice simple attached behavior which pops open an OpenFileDialog when you click on a textbox and puts the filename in the box when you're done. It works maybe 40% of the time but the rest of the time the whole app hangs. The call stack at this point looks like this - [Managed to Native Transition] WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes Debugatron.exe!Debugatron.App.Main() + 0x5e bytes C# [Native to Managed Transition] [Managed to Native Transition] mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes Now, I've seen this kind of thing before when doing some asynchronous stuff but there's none of that going on at that point. The only thread alive is the UI thread! Also, I always get that last debug statement when it does hang. Can anyone point me in the right direction? This one's driving me crazy!

    Read the article

  • WPF DependencyProperty event before content changed

    - by morsanu
    First I will explain the context of the problem, because you might be able to point me in a better direction. I need to implement a undo-redo like system on an object. The object has a series of dependency properties. Some are double, int, string but some are also of DependencyObject type. I need to save the value of the property before it is changed, and for this I added the CoerceValueCallback. public static readonly DependencyProperty MyBackgroundProperty = DependencyProperty.Register("MyBackground", typeof(MyCustomizableBackground), typeof(MyComponent), new UIPropertyMetadata(default(MyCustomizableBackground), null, new CoerceValueCallback(OnPropertyChanged))); In OnPropertyChanged I save the value before it's changed. MyCustomizableBackground is the DependencyObject that has also some dependency properties. The problem is that in this case, where I have a custom object as a property, the OnPropertyChanged method isn't triggered, but when I have a common type, it is triggered.

    Read the article

  • How to keep a local value from being set when a binding fails (so inherited values will propagate)

    - by redoced
    Consider the following scenario: I want to bind the TextElement.FontWeight property to an xml attribute. The xml looks somewhat like this and has arbitrary depth. <text font-weight="bold"> bold text here <inlinetext>more bold text</inlinetext> even more bold text </text> I use hierarchical templating to display the text, no problem there, but having a Setter in the template style like: <Setter Property="TextElement.FontWeight" Value="{Binding XPath=@font-weight}"/> sets the fontweight correctly on the first level, but overwrites the second level with null (as the binding can't find the xpath) which reverts to Fontweight normal. I tried all sorts of things here but nothing quite seems to work. e.g. i used a converter to return UnsetValue, which didn't work. I'm currently trying with: <Setter Property="custom:AttributeInserter.Wrapper" Value="{custom:AttributeInserter Property=TextElement.FontWeight, Binding={Binding XPath=@font-weight}}"/> Codebehind: public static class AttributeInserter { public static AttributeInserterExtension GetWrapper(DependencyObject obj) { return (AttributeInserterExtension)obj.GetValue(WrapperProperty); } public static void SetWrapper(DependencyObject obj, AttributeInserterExtension value) { obj.SetValue(WrapperProperty, value); } // Using a DependencyProperty as the backing store for Wrapper. This enables animation, styling, binding, etc... public static readonly DependencyProperty WrapperProperty = DependencyProperty.RegisterAttached("Wrapper", typeof(AttributeInserterExtension), typeof(AttributeInserter), new UIPropertyMetadata(pcc)); static void pcc(DependencyObject o,DependencyPropertyChangedEventArgs e) { var n=e.NewValue as AttributeInserterExtension; var c = o as FrameworkElement; if (n == null || c==null || n.Property==null || n.Binding==null) return; var bex = c.SetBinding(n.Property, n.Binding); bex.UpdateTarget(); if (bex.Status == BindingStatus.UpdateTargetError) c.ClearValue(n.Property); } } public class AttributeInserterExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } public DependencyProperty Property { get; set; } public Binding Binding { get; set; } } which kinda works, but can't track changes of the property Any ideas? Any links? thx for the help

    Read the article

  • TemplateBinding with Converter - what is wrong?

    - by MartyIX
    I'm creating a game desk. I wanted to specify field size (one field is a square) as a attached property and with this data set value of ViewPort which would draw 2x2 matrix (and tile mode would do the rest of game desk). I'm quite at loss what is wrong because the binding doesn't work. Testing line in XAML for the behaviour I would like to have: <DrawingBrush Viewport="0,0,100,100" ViewportUnits="Absolute" TileMode="None"> The game desk is based on this sample of DrawingPaint: http://msdn.microsoft.com/en-us/library/aa970904.aspx (an image is here) XAML: <Window x:Class="Sokoban.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Sokoban" Title="Window1" Height="559" Width="419"> <Window.Resources> <local:FieldSizeToRectConverter x:Key="fieldSizeConverter" /> <Style x:Key="GameDesk" TargetType="{x:Type Rectangle}"> <Setter Property="local:GameDeskProperties.FieldSize" Value="50" /> <Setter Property="Fill"> <Setter.Value> <!--<DrawingBrush Viewport="0,0,100,100" ViewportUnits="Absolute" TileMode="None">--> <DrawingBrush Viewport="{TemplateBinding local:GameDeskProperties.FieldSize, Converter={StaticResource fieldSizeConverter}}" ViewportUnits="Absolute" TileMode="None"> <DrawingBrush.Drawing> <DrawingGroup> <GeometryDrawing Brush="CornflowerBlue"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,100,100" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="Azure"> <GeometryDrawing.Geometry> <GeometryGroup> <RectangleGeometry Rect="0,0,50,50" /> <RectangleGeometry Rect="50,50,50,50" /> </GeometryGroup> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> </Setter.Value> </Setter> </Style> </Window.Resources> <StackPanel> <Rectangle Style="{StaticResource GameDesk}" Width="300" Height="150" /> </StackPanel> </Window> Converter and property definition: using System; using System.Collections.Generic; using System.Text; using System.Windows.Controls; using System.Windows; using System.Diagnostics; using System.Windows.Data; namespace Sokoban { public class GameDeskProperties : Panel { public static readonly DependencyProperty FieldSizeProperty; static GameDeskProperties() { PropertyChangedCallback fieldSizeChanged = new PropertyChangedCallback(OnFieldSizeChanged); PropertyMetadata fieldSizeMetadata = new PropertyMetadata(50, fieldSizeChanged); FieldSizeProperty = DependencyProperty.RegisterAttached("FieldSize", typeof(int), typeof(GameDeskProperties), fieldSizeMetadata); } public static int GetFieldSize(DependencyObject target) { return (int)target.GetValue(FieldSizeProperty); } public static void SetFieldSize(DependencyObject target, int value) { target.SetValue(FieldSizeProperty, value); } static void OnFieldSizeChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("FieldSize just changed: " + e.NewValue); } } [ValueConversion(/* sourceType */ typeof(int), /* targetType */ typeof(Rect))] public class FieldSizeToRectConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Debug.Assert(targetType == typeof(int)); int fieldSize = int.Parse(value.ToString()); return new Rect(0, 0, 2 * fieldSize, 2 * fieldSize); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // should not be called in our example throw new NotImplementedException(); } } }

    Read the article

  • Why do I get a NullReferenceException when using a style on a ContentPresenter?

    - by Robert Rossney
    I've created this template, which uses a style applied to the ContentPresenter so that I can bind the data object's Column property to Grid.Column, allowing the items to determine for themselves which column of the Grid they go into: <DataTemplate DataType="{x:Type local:MyObject}"> <ItemsControl ItemsSource="{Binding Items}"> <ItemsControl.Resources> <Style TargetType="{x:Type ContentPresenter}"> <Setter Property="Grid.Column" Value="{Binding Column}" /> </Style> </ItemsControl.Resources> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> </Grid> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </DataTemplate> When I run the program, I get a NullReferenceException. The beginning of the hilariously long stack trace: at System.Windows.StyleHelper.ApplyAutoAliasRules(OptimizedTemplateContent optimizedTemplateContent, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate, FrugalStructList`1& childRecordFromChildIndex, FrugalStructList`1& triggerSourceRecordFromChildIndex, FrugalStructList`1& resourceDependents, HybridDictionary& dataTriggerRecordFromBinding, Boolean& hasInstanceValues) at System.Windows.StyleHelper.ProcessTemplateContent(FrameworkTemplate frameworkTemplate, FrugalStructList`1& childRecordFromChildIndex, FrugalStructList`1& triggerSourceRecordFromChildIndex, FrugalStructList`1& resourceDependents, ItemStructList`1& eventDependents, HybridDictionary& dataTriggerRecordFromBinding, HybridDictionary childIndexFromChildID, Boolean& hasInstanceValues) at System.Windows.StyleHelper.SealTemplate(FrameworkTemplate frameworkTemplate, Boolean& isSealed, FrameworkElementFactory templateRoot, TriggerCollection triggers, ResourceDictionary resources, HybridDictionary childIndexFromChildID, FrugalStructList`1& childRecordFromChildIndex, FrugalStructList`1& triggerSourceRecordFromChildIndex, FrugalStructList`1& containerDependents, FrugalStructList`1& resourceDependents, ItemStructList`1& eventDependents, HybridDictionary& triggerActions, HybridDictionary& dataTriggerRecordFromBinding, Boolean& hasInstanceValues, EventHandlersStore& eventHandlersStore) at System.Windows.FrameworkTemplate.Seal() at System.Windows.StyleHelper.UpdateTemplateCache(FrameworkElement fe, FrameworkTemplate oldTemplate, FrameworkTemplate newTemplate, DependencyProperty templateProperty) at System.Windows.Controls.ContentPresenter.OnTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) ...etc. It's not the binding. I still get the error if I explicitly set the value in the style's setter to 0, say. And the error vanishes if I remove the style, though then all of the items end up in column 0. What's going on here? And how do I debug a problem like this?

    Read the article

  • Demystifying Silverlight Dependency Properties

    - by dwahlin
    I have the opportunity to teach a lot of people about Silverlight (amongst other technologies) and one of the topics that definitely confuses people initially is the concept of dependency properties. I confess that when I first heard about them my initial thought was “Why do we need a specialized type of property?” While you can certainly use standard CLR properties in Silverlight applications, Silverlight relies heavily on dependency properties for just about everything it does behind the scenes. In fact, dependency properties are an essential part of the data binding, template, style and animation functionality available in Silverlight. They simply back standard CLR properties. In this post I wanted to put together a (hopefully) simple explanation of dependency properties and why you should care about them if you’re currently working with Silverlight or looking to move to it.   What are Dependency Properties? XAML provides a great way to define layout controls, user input controls, shapes, colors and data binding expressions in a declarative manner. There’s a lot that goes on behind the scenes in order to make XAML work and an important part of that magic is the use of dependency properties. If you want to bind data to a property, style it, animate it or transform it in XAML then the property involved has to be a dependency property to work properly. If you’ve ever positioned a control in a Canvas using Canvas.Left or placed a control in a specific Grid row using Grid.Row then you’ve used an attached property which is a specialized type of dependency property. Dependency properties play a key role in XAML and the overall Silverlight framework. Any property that you bind, style, template, animate or transform must be a dependency property in Silverlight applications. You can programmatically bind values to controls and work with standard CLR properties, but if you want to use the built-in binding expressions available in XAML (one of my favorite features) or the Binding class available through code then dependency properties are a necessity. Dependency properties aren’t needed in every situation, but if you want to customize your application very much you’ll eventually end up needing them. For example, if you create a custom user control and want to expose a property that consumers can use to change the background color, you have to define it as a dependency property if you want bindings, styles and other features to be available for use. Now that the overall purpose of dependency properties has been discussed let’s take a look at how you can create them. Creating Dependency Properties When .NET first came out you had to write backing fields for each property that you defined as shown next: Brush _ScheduleBackground; public Brush ScheduleBackground { get { return _ScheduleBackground; } set { _ScheduleBackground = value; } } Although .NET 2.0 added auto-implemented properties (for example: public Brush ScheduleBackground { get; set; }) where the compiler would automatically generate the backing field used by get and set blocks, the concept is still the same as shown in the above code; a property acts as a wrapper around a field. Silverlight dependency properties replace the _ScheduleBackground field shown in the previous code and act as the backing store for a standard CLR property. The following code shows an example of defining a dependency property named ScheduleBackgroundProperty: public static readonly DependencyProperty ScheduleBackgroundProperty = DependencyProperty.Register("ScheduleBackground", typeof(Brush), typeof(Scheduler), null);   Looking through the code the first thing that may stand out is that the definition for ScheduleBackgroundProperty is marked as static and readonly and that the property appears to be of type DependencyProperty. This is a standard pattern that you’ll use when working with dependency properties. You’ll also notice that the property explicitly adds the word “Property” to the name which is another standard you’ll see followed. In addition to defining the property, the code also makes a call to the static DependencyProperty.Register method and passes the name of the property to register (ScheduleBackground in this case) as a string. The type of the property, the type of the class that owns the property and a null value (more on the null value later) are also passed. In this example a class named Scheduler acts as the owner. The code handles registering the property as a dependency property with the call to Register(), but there’s a little more work that has to be done to allow a value to be assigned to and retrieved from the dependency property. The following code shows the complete code that you’ll typically use when creating a dependency property. You can find code snippets that greatly simplify the process of creating dependency properties out on the web. The MVVM Light download available from http://mvvmlight.codeplex.com comes with built-in dependency properties snippets as well. public static readonly DependencyProperty ScheduleBackgroundProperty = DependencyProperty.Register("ScheduleBackground", typeof(Brush), typeof(Scheduler), null); public Brush ScheduleBackground { get { return (Brush)GetValue(ScheduleBackgroundProperty); } set { SetValue(ScheduleBackgroundProperty, value); } } The standard CLR property code shown above should look familiar since it simply wraps the dependency property. However, you’ll notice that the get and set blocks call GetValue and SetValue methods respectively to perform the appropriate operation on the dependency property. GetValue and SetValue are members of the DependencyObject class which is another key component of the Silverlight framework. Silverlight controls and classes (TextBox, UserControl, CompositeTransform, DataGrid, etc.) ultimately derive from DependencyObject in their inheritance hierarchy so that they can support dependency properties. Dependency properties defined in Silverlight controls and other classes tend to follow the pattern of registering the property by calling Register() and then wrapping the dependency property in a standard CLR property (as shown above). They have a standard property that wraps a registered dependency property and allows a value to be assigned and retrieved. If you need to expose a new property on a custom control that supports data binding expressions in XAML then you’ll follow this same pattern. Dependency properties are extremely useful once you understand why they’re needed and how they’re defined. Detecting Changes and Setting Defaults When working with dependency properties there will be times when you want to assign a default value or detect when a property changes so that you can keep the user interface in-sync with the property value. Silverlight’s DependencyProperty.Register() method provides a fourth parameter that accepts a PropertyMetadata object instance. PropertyMetadata can be used to hook a callback method to a dependency property. The callback method is called when the property value changes. PropertyMetadata can also be used to assign a default value to the dependency property. By assigning a value of null for the final parameter passed to Register() you’re telling the property that you don’t care about any changes and don’t have a default value to apply. Here are the different constructor overloads available on the PropertyMetadata class: PropertyMetadata Constructor Overload Description PropertyMetadata(Object) Used to assign a default value to a dependency property. PropertyMetadata(PropertyChangedCallback) Used to assign a property changed callback method. PropertyMetadata(Object, PropertyChangedCalback) Used to assign a default property value and a property changed callback.   There are many situations where you need to know when a dependency property changes or where you want to apply a default. Performing either task is easily accomplished by creating a new instance of the PropertyMetadata class and passing the appropriate values to its constructor. The following code shows an enhanced version of the initial dependency property code shown earlier that demonstrates these concepts: public Brush ScheduleBackground { get { return (Brush)GetValue(ScheduleBackgroundProperty); } set { SetValue(ScheduleBackgroundProperty, value); } } public static readonly DependencyProperty ScheduleBackgroundProperty = DependencyProperty.Register("ScheduleBackground", typeof(Brush), typeof(Scheduler), new PropertyMetadata(new SolidColorBrush(Colors.LightGray), ScheduleBackgroundChanged)); private static void ScheduleBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var scheduler = d as Scheduler; scheduler.Background = e.NewValue as Brush; } The code wires ScheduleBackgroundProperty to a property change callback method named ScheduleBackgroundChanged. What’s interesting is that this callback method is static (as is the dependency property) so it gets passed the instance of the object that owns the property that has changed (otherwise we wouldn’t be able to get to the object instance). In this example the dependency object is cast to a Scheduler object and its Background property is assigned to the new value of the dependency property. The code also handles assigning a default value of LightGray to the dependency property by creating a new instance of a SolidColorBrush. To Sum Up In this post you’ve seen the role of dependency properties and how they can be defined in code. They play a big role in XAML and the overall Silverlight framework. You can think of dependency properties as being replacements for fields that you’d normally use with standard CLR properties. In addition to a discussion on how dependency properties are created, you also saw how to use the PropertyMetadata class to define default dependency property values and hook a dependency property to a callback method. The most important thing to understand with dependency properties (especially if you’re new to Silverlight) is that they’re needed if you want a property to support data binding, animations, transformations and styles properly. Any time you create a property on a custom control or user control that has these types of requirements you’ll want to pick a dependency property over of a standard CLR property with a backing field. There’s more that can be covered with dependency properties including a related property called an attached property….more to come.

    Read the article

  • Building on someone else's DefaultButton Silverlight work...

    - by KyleBurns
    This week I was handed a "simple" requirement - have a search screen execute its search when the user pressed the Enter key instead of having to move hands from keyboard to mouse and click Search.  That is a reasonable request that has been met for years both in Windows and Web apps.  I did a quick scan for code to pilfer and found Patrick Cauldwell's Blog posting "A 'Default Button' In Silverlight".  This posting was a great start and I'm glad that the basic work had been done for me, but I ran into one issue - when using bound textboxes (I'm a die-hard MVVM enthusiast when it comes to Silverlight development), the search was being executed before the textbox I was in when the Enter key was pressed updated its bindings.  With a little bit of reflection work, I think I have found a good generic solution that builds upon Patrick's to make it more binding-friendly.  Also, I wanted to set the DefaultButton at a higher level than on each TextBox (or other control for that matter), so the use of mine is intended to be set somewhere such as the LayoutRoot or other high level control and will apply to all controls beneath it in the control tree.  I haven't tested this on controls that treat the Enter key special themselves in the mix. The real change from Patrick's solution here is that in the KeyUp event, I grab the source of the KeyUp event (in my case the textbox containing search criteria) and loop through the static fields on the element's type looking for DependencyProperty instances.  When I find a DependencyProperty, I grab the value and query for bindings.  Each time I find a binding, UpdateSource is called to make sure anything bound to any property of the field has the opportunity to update before the action represented by the DefaultButton is executed. Here's the code: public class DefaultButtonService { public static DependencyProperty DefaultButtonProperty = DependencyProperty.RegisterAttached("DefaultButton", typeof (Button), typeof (DefaultButtonService), new PropertyMetadata (null, DefaultButtonChanged)); private static void DefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var uiElement = d as UIElement; var button = e.NewValue as Button; if (uiElement != null && button != null) { uiElement.KeyUp += (sender, arg) => { if (arg.Key == Key.Enter) { var element = arg.OriginalSource as FrameworkElement; if (element != null) { UpdateBindings(element); } if (button.IsEnabled) { button.Focus(); var peer = new ButtonAutomationPeer(button); var invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider; if (invokeProv != null) invokeProv.Invoke(); arg.Handled = true; } } }; } } public static DefaultButtonService GetDefaultButton(UIElement obj) { return (DefaultButtonService) obj.GetValue(DefaultButtonProperty); } public static void SetDefaultButton(DependencyObject obj, DefaultButtonService button) { obj.SetValue(DefaultButtonProperty, button); } public static void UpdateBindings(FrameworkElement element) { element.GetType().GetFields(BindingFlags.Public | BindingFlags.Static).ForEach(field => { if (field.FieldType.IsAssignableFrom(typeof(DependencyProperty))) { try { var dp = field.GetValue(null) as DependencyProperty; if (dp != null) { var binding = element.GetBindingExpression(dp); if (binding != null) { binding.UpdateSource(); } } } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { // swallow exceptions } } }); } }

    Read the article

  • Workarounds for supporting MVVM in the Silverlight ContextMenu service

    - by cibrax
    As I discussed in my last post, some of the Silverlight controls does not support MVVM quite well out of the box without specific customizations. The Context Menu is another control that requires customizations for enabling data binding on the menu options. There are a few things that you might want to expose as view model for a menu item, such as the Text, the associated icon or the command that needs to be executed. That view model should look like this, public class MenuItemModel { public string Name { get; set; } public ICommand Command { get; set; } public Image Icon { get; set; } public object CommandParameter { get; set; } } This is how you can modify the built-in control to support data binding on the model above, public class CustomContextMenu : ContextMenu { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem(); Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   Binding commandParameter = new Binding("CommandParameter"); item.SetBinding(CustomMenuItem.CommandParameterProperty, commandParameter);   return item; } }   public class CustomMenuItem : MenuItem { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem();   Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   return item; } } The change is very similar to the one I made in the TreeView for manually data binding some of the Menu item properties to the model. Once you applied that change in the control, you can define it in your XAML like this. <toolkit:ContextMenuService.ContextMenu> <e:CustomContextMenu ItemsSource="{Binding MenuItems}"> <e:CustomContextMenu.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <ContentPresenter Margin="0 0 4 0" Content="{Binding Icon}" /> <TextBlock Margin="0" Text="{Binding Name, Mode=OneWay}" FontSize="12"/> </StackPanel> </DataTemplate> </e:CustomContextMenu.ItemTemplate> </e:CustomContextMenu> </toolkit:ContextMenuService.ContextMenu> The property MenuItems associated to the “ItemsSource” in the parent model just returns a list of supported options (menu items) in the context menu. this.menuItems = new MenuItemModel[] { new MenuItemModel { Name = "My Command", Command = new RelayCommand(OnCommandClick), Icon = ImageLoader.GetIcon("command.png") } }; The only problem I found so far with this approach is that the context menu service does not support a HierarchicalDataTemplate in case you want to have an hierarchy in the context menu (MenuItem –> Sub menu items), but I guess we can live without that.

    Read the article

  • wpf 4.0 datagrid template column two-way binding problem

    - by rouwlee
    Hello all! I'm using the datagrid from wpf 4.0. This has a TemplateColumn containing a checkbox. The IsChecked property of the checkbox is set via binding. The problem is that even if I specify the binding mode explicitly to be TwoWay, it works only in one direction. I have to mention that the same code works perfectly in .net 3.5 with the datagrid from the wpf toolkit. Please take a look at the .xaml and .cs contents. Thanks in advance, Roland <Window.Resources> <DataTemplate x:Key="IsSelectedColumnTemplate"> <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" /> </DataTemplate> </Window.Resources> <Grid> <DataGrid x:Name="dataGrid" AutoGenerateColumns="false" CanUserAddRows="False" CanUserDeleteRows="False" HeadersVisibility="Column" ItemsSource="{Binding}" > <DataGrid.Columns> <DataGridTemplateColumn Header="Preselected" x:Name="myIsSelectedColumn" CellTemplate="{StaticResource IsSelectedColumnTemplate}" CanUserSort="True" SortMemberPath="Orientation" Width="Auto" /> </DataGrid.Columns> </DataGrid> </Grid> and the related .cs content: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); ObservableCollection<DataObject> DataSource = new ObservableCollection<DataObject>(); DataSource.Add(new DataObject()); dataGrid.ItemsSource = DataSource; } } public class DataObject : DependencyObject { public bool IsSelected { get { return (bool)GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } // Using a DependencyProperty as the backing store for IsSelected. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(DataObject), new UIPropertyMetadata(false, OnIsSelectedChanged)); private static void OnIsSelectedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { // this part is not reached } }

    Read the article

  • WPF: ListView inside LIstViewItem: How to support button_click

    - by Bartek
    Hi I have problem with using buttons that are placed in the itemtemplate of the listview which is placed in the itemtemplate of the outer listview. I'll try to simplify the code to show only the idea. I have a objects collection which looks like this: Main object contains a list of innerObjects. Every innerObject contains a list of objects that contain some strings. mainObject listItem innerListItem string string innerListItem string string listItem innerListItem string string I set a mainObject as a itemsSource to the ListView. This listView has a ItemTemplate. This ItemTemplate contains some buttons and inner ListView. Inner ListView also has the item template that contains a button (deleteButton). Pressing this deleteButton I want to delete items (innerListItem) for which this button was created. I can use such functionality when I have a sigle listView. private void clearAndList_Click(object sender, RoutedEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is System.Windows.Controls.ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) { return; } ANDconditionsList andList = (ANDconditionsList)ConditionsList.ItemContainerGenerator.ItemFromContainer(dep); orConditionsList.RemoveConditionsSet(andList); } I can't use the same functionality because I can only use the name of the ConditionsList which is the mail listview. The idea is to find the innerlistview and use it instead of ConditionsList, however I don't know if it will work. If anyone have some samples concerning using listview in listview or how to operate the button in a different way please help me

    Read the article

  • Style Trigger on Attached Property

    - by vanja.
    I have created my own Attached Property like this: public static class LabelExtension { public static bool GetSelectable(DependencyObject obj) { return (bool)obj.GetValue(SelectableProperty); } public static void SetSelectable(DependencyObject obj, bool value) { obj.SetValue(SelectableProperty, value); } // Using a DependencyProperty as the backing store for Selectable. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectableProperty = DependencyProperty.RegisterAttached("Selectable", typeof(bool), typeof(Label), new UIPropertyMetadata(false)); } And then I'm trying to create a style with a trigger that depends on it: <!--Label--> <Style TargetType="{x:Type Label}"> <Style.Triggers> <Trigger Property="Util:LabelExtension.Selectable" Value="True"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Label}"> <TextBox IsReadOnly="True" Text="{TemplateBinding Content}" /> </ControlTemplate> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> But I'm getting a run time exception: Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'. Error at object 'System.Windows.Trigger' in markup file How can I access the value of the attached property in a style trigger? I have tried using a DataTrigger with a RelativeSource binding but it wasn't pulling the value through.

    Read the article

  • How can I handle events within my custom control?

    - by highone
    I am not looking to create new events. I need to create a canvas control that optionally fades in or out depending on whether or not the mouse is over it. The code below probably explains what I want to do better than I can. private Storyboard fadeInStoryboard; private Storyboard fadeOutStoryboard; public FadingOptionPanel() { InitializeComponent(); } public static readonly DependencyProperty FadeEnabledProperty = DependencyProperty.Register("IsFadeEnabled", typeof(bool), typeof(FadingOptionPanel), new FrameworkPropertyMetadata(true, OnFadeEnabledPropertyChanged, OnCoerceFadeEnabledProperty)); public bool IsFadeEnabled { get { return (bool)GetValue(FadeEnabledProperty); } set { SetValue(FadeEnabledProperty, value); } } private static void OnFadeEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { } private static object OnCoerceFadeEnabledProperty(DependencyObject sender, object data) { if (data.GetType() != typeof(bool)) { data = true; } return data; } private void FadingOptionPanel_MouseEnter(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeInStoryboard.Begin(this); } } private void FadingOptionPanel_MouseLeave(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeOutStoryboard.Begin(this); } } private void FadingOptionsPanel_Loaded(object sender, RoutedEventArgs e) { //Initialize Fade In Animation DoubleAnimation fadeInDoubleAnimation = new DoubleAnimation(); fadeInDoubleAnimation.From = 0; fadeInDoubleAnimation.To = 1; fadeInDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.5)); fadeInStoryboard = new Storyboard(); fadeInStoryboard.Children.Add(fadeInDoubleAnimation); Storyboard.SetTargetName(fadeInDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeInDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); //Initialize Fade Out Animation DoubleAnimation fadeOutDoubleAnimation = new DoubleAnimation(); fadeOutDoubleAnimation.From = 1; fadeOutDoubleAnimation.To = 0; fadeOutDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.2)); fadeOutStoryboard = new Storyboard(); fadeOutStoryboard.Children.Add(fadeOutDoubleAnimation); Storyboard.SetTargetName(fadeOutDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeOutDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); } I originally was using this code inside a usercontrol instead of a custom control before I found out that usercontrols don't support content.

    Read the article

  • Moving to .net 4 results in System.Transactions Critical: 0

    - by john
    Hi I have fully working project in .net 3.5SP1, with EF 1 ORM. I tried to upgrade to .net 4. No issue while upgrading... Then i ran the project and got a NullExecptionError, with no stack trace... and no way to debug. Looking at the output windows i can read this: System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>OTCSouscriptions.vshost.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Object reference not set to an instance of an object.</Message><StackTrace> at System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry&amp;amp; entry) at System.Windows.FrameworkTemplate.ReceivePropertySet(Object targetObject, XamlMember member, Object value, DependencyObject templatedParent) at System.Windows.FrameworkTemplate.&amp;lt;&amp;gt;c__DisplayClass6.&amp;lt;LoadOptimizedTemplateContent&amp;gt;b__4(Object sender, XamlSetValueEventArgs setArgs) at System.Xaml.XamlObjectWriter.OnSetValue(Object eventSender, XamlMember member, Object value) at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent) at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx) at System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx) at System.Xaml.XamlObjectWriter.WriteEndObject() at System.Xaml.XamlWriter.WriteNode(XamlReader reader) at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter) Any help appreciated... Thanks John

    Read the article

  • Silverlight WinDg Memory Release Issue

    - by Chris Newton
    Hi, I have used WinDbg succesfully on a number of occasions to track down and fix memory leaks (or more accurately the CLRs inability to garbage collect a released object), but am stuck with one particular control. The control is displayed within a child window and when the window is closed a reference to the control remains and cannot be garbage collected. I have resolved what I believe to be the majority of the issues that could have caused the leak, but the !gcroot of the affected object is not clear (to me at least) as to what is still holding on to this object. The ouput is always the same regardless of the content being presented in the child window: DOMAIN(03FB7238):HANDLE(Pinned):79b12f8:Root: 06704260(System.Object[])- 05719f00(System.Collections.Generic.Dictionary2[[System.IntPtr, mscorlib],[System.Object, mscorlib]])-> 067c1310(System.Collections.Generic.Dictionary2+Entry[[System.IntPtr, mscorlib],[System.Object, mscorlib]][])- 064d42b0(System.Windows.Controls.Grid)- 064d4314(System.Collections.Generic.Dictionary2[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]])-> 064d4360(System.Collections.Generic.Dictionary2+Entry[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]][])- 064d3860(System.Windows.Controls.Border)- 064d4218(System.Collections.Generic.Dictionary2[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]])-> 064d4264(System.Collections.Generic.Dictionary2+Entry[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]][])- 064d3bfc(System.Windows.Controls.ContentPresenter)- 064d3d64(System.Collections.Generic.Dictionary2[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]])-> 064d3db0(System.Collections.Generic.Dictionary2+Entry[[MS.Internal.IManagedPeerBase, System.Windows],[System.Object, mscorlib]][])- 064d3dec(System.Collections.Generic.Dictionary2[[System.UInt32, mscorlib],[System.Windows.DependencyObject, System.Windows]])-> 064d3e38(System.Collections.Generic.Dictionary2+Entry[[System.UInt32, mscorlib],[System.Windows.DependencyObject, System.Windows]][])- 06490b04(Insurer.Analytics.SharedResources.Controls.HistoricalKPIViewerControl) If anyone has any ideas about what could potentially be the problem, or if you require more information, please let me know. Kind Regards, Chris

    Read the article

  • Dependency Properties, change notification and setting values in the constructor

    - by stefan.at.wpf
    Hello, I have a clas with 3 dependency properties A,B,C. The values of these properties are set by the constructor and every time one of the properties A, B or C changes, the method recalculate() is called. Now during execution of the constructor these method is called 3 times, because the 3 properties A, B, C are changed. Hoewever this isn't necessary as the method recalculate() can't do anything really useful without all 3 properties set. So what's the best way for property change notification but circumventing this change notification in the constructor? I thought about adding the property changed notification in the constructor, but then each object of the DPChangeSample class would always add more and more change notifications. Thanks for any hint! class DPChangeSample : DependencyObject { public static DependencyProperty AProperty = DependencyProperty.Register("A", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged)); public static DependencyProperty BProperty = DependencyProperty.Register("B", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged)); public static DependencyProperty CProperty = DependencyProperty.Register("C", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged)); private static void propertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((DPChangeSample)d).recalculate(); } private void recalculate() { // Using A, B, C do some cpu intensive caluclations } public DPChangeSample(int a, int b, int c) { SetValue(AProperty, a); SetValue(BProperty, b); SetValue(CProperty, c); } }

    Read the article

  • How can I bind to a helper property in Silverlight

    - by Matt
    For the sake of argument, here's a simple person class public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs( "FirstName" )); } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); } } } I want to go about creating a readonly property like this public string FullName { get { return FirstName + " " + LastName; } } How does binding work in this scenario? I've tried adding a DependancyProperty and raised the PropertyChanged event for the fullname. Basically I just want to have a property that I can bind to that returns the fullname of a user whenever the first or last name changes. Here's the final class I'm using with the modifications. public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public static readonly DependencyProperty FullNameProperty = DependencyProperty.Register( "FullName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "FirstName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string FullName { get { return GetValue( FirstNameProperty ) + " " + GetValue( LastNameProperty ); } } }

    Read the article

  • GetLocalValueEnumerator() Not Returning All Properties

    - by a_hardin
    I am trying to perform validation in my WPF application using the solution in Detecting WPF Validation Errors. public static bool IsValid(DependencyObject parent) { // Validate all the bindings on the parent bool valid = true; LocalValueEnumerator localValues = parent.GetLocalValueEnumerator(); while (localValues.MoveNext()) { LocalValueEntry entry = localValues.Current; if (BindingOperations.IsDataBound(parent, entry.Property)) { Binding binding = BindingOperations.GetBinding(parent, entry.Property); foreach (ValidationRule rule in binding.ValidationRules) { ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null); if (!result.IsValid) { BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property); System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null)); valid = false; } } } } // Validate all the bindings on the children for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (!IsValid(child)) { valid = false; } } return valid; } The problem I am running into is that when I step through the code for a TextBox, I'm not getting the Text property. The only properties I get are "PageHeight", "Instance", and "UndoManagerInstance". Therefore, I can not Validate the rules for the binding on the TextBox. Does anyone have any idea why I wouldn't be getting the correct properties? Is there another way to force validaton on controls in WPF? I haven't been able to find anyone else who has had this problem. Update: The TextBoxes I am trying to validate are within a DataTemplate. I found that if I copy one of the TextBoxes and place it directly in the Window, I am able to get the data. Using Woodstock, I saw that the data source for the TextBoxes in the template is "ParentTemplate", but it's "Local" for the TextBox outside of the template. So, the question now is, how can I get the DependencyProperties for controls inside a DataTemplate?

    Read the article

  • WPF Blurry Images - Bitmap Class

    - by Luke
    I am using the following sample at http://blogs.msdn.com/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx within VB.NET. The code is shown below. I am having a problem when my application loads the CPU is pegging 50-70%. I have determined that the problem is with the Bitmap class. The OnLayoutUpdated() method is calling the InvalidateVisual() continously. This is because some points are not returning as equal but rather, Point(0.0,-0.5) Can anyone see any bugs within this code or know a better implmentation for pixel snapping a Bitmap image so it is not blurry? p.s. The sample code was in C#, however I believe that it was converted correctly. Imports System Imports System.Collections.Generic Imports System.Windows Imports System.Windows.Media Imports System.Windows.Media.Imaging Class Bitmap Inherits FrameworkElement ' Use FrameworkElement instead of UIElement so Data Binding works as expected Private _sourceDownloaded As EventHandler Private _sourceFailed As EventHandler(Of ExceptionEventArgs) Private _pixelOffset As Windows.Point Public Sub New() _sourceDownloaded = New EventHandler(AddressOf OnSourceDownloaded) _sourceFailed = New EventHandler(Of ExceptionEventArgs)(AddressOf OnSourceFailed) AddHandler LayoutUpdated, AddressOf OnLayoutUpdated End Sub Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(BitmapSource), GetType(Bitmap), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.AffectsMeasure, New PropertyChangedCallback(AddressOf Bitmap.OnSourceChanged))) Public Property Source() As BitmapSource Get Return DirectCast(GetValue(SourceProperty), BitmapSource) End Get Set(ByVal value As BitmapSource) SetValue(SourceProperty, value) End Set End Property Public Shared Function FindParentWindow(ByVal child As DependencyObject) As Window Dim parent As DependencyObject = VisualTreeHelper.GetParent(child) 'Check if this is the end of the tree If parent Is Nothing Then Return Nothing End If Dim parentWindow As Window = TryCast(parent, Window) If parentWindow IsNot Nothing Then Return parentWindow Else ' Use recursion until it reaches a Window Return FindParentWindow(parent) End If End Function Public Event BitmapFailed As EventHandler(Of ExceptionEventArgs) ' Return our measure size to be the size needed to display the bitmap pixels. ' ' Use MeasureOverride instead of MeasureCore so Data Binding works as expected. ' Protected Overloads Overrides Function MeasureCore(ByVal availableSize As Size) As Size Protected Overloads Overrides Function MeasureOverride(ByVal availableSize As Size) As Size Dim measureSize As New Size() Dim bitmapSource As BitmapSource = Source If bitmapSource IsNot Nothing Then Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If Me.VisualParent IsNot Nothing Then Dim window As Window = window.GetWindow(Me.VisualParent) If window IsNot Nothing Then ps = PresentationSource.FromVisual(window.GetWindow(Me.VisualParent)) ElseIf FindParentWindow(Me) IsNot Nothing Then ps = PresentationSource.FromVisual(FindParentWindow(Me)) End If End If ' If ps IsNot Nothing Then Dim fromDevice As Matrix = ps.CompositionTarget.TransformFromDevice Dim pixelSize As New Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight) Dim measureSizeV As Vector = fromDevice.Transform(pixelSize) measureSize = New Size(measureSizeV.X, measureSizeV.Y) Else measureSize = New Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight) End If End If Return measureSize End Function Protected Overloads Overrides Sub OnRender(ByVal dc As DrawingContext) Dim bitmapSource As BitmapSource = Me.Source If bitmapSource IsNot Nothing Then _pixelOffset = GetPixelOffset() ' Render the bitmap offset by the needed amount to align to pixels. dc.DrawImage(bitmapSource, New Rect(_pixelOffset, DesiredSize)) End If End Sub Private Shared Sub OnSourceChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) Dim bitmap As Bitmap = DirectCast(d, Bitmap) Dim oldValue As BitmapSource = DirectCast(e.OldValue, BitmapSource) Dim newValue As BitmapSource = DirectCast(e.NewValue, BitmapSource) If ((oldValue IsNot Nothing) AndAlso (bitmap._sourceDownloaded IsNot Nothing)) AndAlso (Not oldValue.IsFrozen AndAlso (TypeOf oldValue Is BitmapSource)) Then RemoveHandler DirectCast(oldValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded RemoveHandler DirectCast(oldValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5 End If If ((newValue IsNot Nothing) AndAlso (TypeOf newValue Is BitmapSource)) AndAlso Not newValue.IsFrozen Then AddHandler DirectCast(newValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded AddHandler DirectCast(newValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5 End If End Sub Private Sub OnSourceDownloaded(ByVal sender As Object, ByVal e As EventArgs) InvalidateMeasure() InvalidateVisual() End Sub Private Sub OnSourceFailed(ByVal sender As Object, ByVal e As ExceptionEventArgs) Source = Nothing ' setting a local value seems scetchy... RaiseEvent BitmapFailed(Me, e) End Sub Private Sub OnLayoutUpdated(ByVal sender As Object, ByVal e As EventArgs) ' This event just means that layout happened somewhere. However, this is ' what we need since layout anywhere could affect our pixel positioning. Dim pixelOffset As Windows.Point = GetPixelOffset() If Not AreClose(pixelOffset, _pixelOffset) Then InvalidateVisual() End If End Sub ' Gets the matrix that will convert a Windows.Point from "above" the ' coordinate space of a visual into the the coordinate space ' "below" the visual. Private Function GetVisualTransform(ByVal v As Visual) As Matrix If v IsNot Nothing Then Dim m As Matrix = Matrix.Identity Dim transform As Transform = VisualTreeHelper.GetTransform(v) If transform IsNot Nothing Then Dim cm As Matrix = transform.Value m = Matrix.Multiply(m, cm) End If Dim offset As Vector = VisualTreeHelper.GetOffset(v) m.Translate(offset.X, offset.Y) Return m End If Return Matrix.Identity End Function Private Function TryApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean, ByVal throwOnError As Boolean, ByRef success As Boolean) As Windows.Point success = True If v IsNot Nothing Then Dim visualTransform As Matrix = GetVisualTransform(v) If inverse Then If Not throwOnError AndAlso Not visualTransform.HasInverse Then success = False Return New Windows.Point(0, 0) End If visualTransform.Invert() End If Point = visualTransform.Transform(Point) End If Return Point End Function Private Function ApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean) As Windows.Point Dim success As Boolean = True Return TryApplyVisualTransform(Point, v, inverse, True, success) End Function Private Function GetPixelOffset() As Windows.Point Dim pixelOffset As New Windows.Point() Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If ps IsNot Nothing Then Dim rootVisual As Visual = ps.RootVisual ' Transform (0,0) from this element up to pixels. pixelOffset = Me.TransformToAncestor(rootVisual).Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, False) pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset) ' Round the origin to the nearest whole pixel. pixelOffset.X = Math.Round(pixelOffset.X) pixelOffset.Y = Math.Round(pixelOffset.Y) ' Transform the whole-pixel back to this element. pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, True) pixelOffset = rootVisual.TransformToDescendant(Me).Transform(pixelOffset) End If Return pixelOffset End Function Private Function AreClose(ByVal Point1 As Windows.Point, ByVal Point2 As Windows.Point) As Boolean Return AreClose(Point1.X, Point2.X) AndAlso AreClose(Point1.Y, Point2.Y) End Function Private Function AreClose(ByVal value1 As Double, ByVal value2 As Double) As Boolean If value1 = value2 Then Return True End If Dim delta As Double = value1 - value2 Return ((delta < 0.00000153) AndAlso (delta > -0.00000153)) End Function End Class

    Read the article

  • Workarounds for supporting MVVM in the Silverlight TreeView Control

    - by cibrax
    MVVM (Model-View-ViewModel) is the pattern that you will typically choose for building testable user interfaces either in WPF or Silverlight. This pattern basically relies on the data binding support in those two technologies for mapping an existing model class (the view model) to the different parts of the UI or view. Unfortunately, MVVM was not threated as first citizen for some of controls released out of the box in the Silverlight runtime or the Silverlight toolkit. That means that using data binding for implementing MVVM is not always something trivial and usually requires some customization in the existing controls. In ran into different problems myself trying to fully support data binding in controls like the tree view or the context menu or things like drag & drop.  For that reason, I decided to write this post to show how the tree view control or the tree view items can be customized to support data binding in many of its properties. In first place, you will typically use a tree view for showing hierarchical data so the view model somehow must reflect that hierarchy. An easy way to implement hierarchy in a model is to use a base item element like this one, public abstract class TreeItemModel { public abstract IEnumerable<TreeItemModel> Children; } You can later derive your concrete model classes from that base class. For example, public class CustomerModel { public string FullName { get; set; } public string Address { get; set; } public IEnumerable<OrderModel> Orders { get; set; } }   public class CustomerTreeItemModel : TreeItemModel { public CustomerTreeItemModel(CustomerModel customer) { }   public override IEnumerable<TreeItemModel> Children { get { // Return orders } } } The Children property in the CustomerTreeItem model implementation can return for instance an ObservableCollection<TreeItemModel> with the orders, so the tree view will automatically subscribe to all the changes in the collection. You can bind this model to the tree view control in the UI by using a Hierarchical data template. <e:TreeView x:Name="TreeView" ItemsSource="{Binding Customers}"> <e:TreeView.ItemTemplate> <sdk:HierarchicalDataTemplate ItemsSource="{Binding Children}"> <!-- TEMPLATE --> </sdk:HierarchicalDataTemplate> </e:TreeView.ItemTemplate> </e:TreeView> An interesting behavior with the Children property and the Hierarchical data template is that the Children property is only invoked before the expansion, so you can use lazy load at this point (The tree view control will not expand the whole tree in the first expansion). The problem with using MVVM in this control is that you can not bind properties in model with specific properties of the TreeView item such as IsSelected or IsExpanded. Here is where you need to customize the existing tree view control to support data binding in tree items. public class CustomTreeView : TreeView { public CustomTreeView() { }   protected override DependencyObject GetContainerForItemOverride() { CustomTreeViewItem tvi = new CustomTreeViewItem(); Binding expandedBinding = new Binding("IsExpanded"); expandedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsExpandedProperty, expandedBinding); Binding selectedBinding = new Binding("IsSelected"); selectedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsSelectedProperty, selectedBinding); return tvi; } }   public class CustomTreeViewItem : TreeViewItem { public CustomTreeViewItem() { }   protected override DependencyObject GetContainerForItemOverride() { CustomTreeViewItem tvi = new CustomTreeViewItem(); Binding expandedBinding = new Binding("IsExpanded"); expandedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsExpandedProperty, expandedBinding); Binding selectedBinding = new Binding("IsSelected"); selectedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsSelectedProperty, selectedBinding); return tvi; } } You basically need to derive the TreeView and TreeViewItem controls to manually add a binding for the properties you need. In the example above, I am adding a binding for the “IsExpanded” and “IsSelected” properties in the items. The model for the tree items now needs to be extended to support those properties as well, public abstract class TreeItemModel : INotifyPropertyChanged { bool isExpanded = false; bool isSelected = false;   public abstract IEnumerable<TreeItemModel> Children { get; }   public bool IsExpanded { get { return isExpanded; } set { isExpanded = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsExpanded")); } }   public bool IsSelected { get { return isSelected; } set { isSelected = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsSelected")); } }   public event PropertyChangedEventHandler PropertyChanged; } However, as soon as you use this custom tree view control, you lose all the automatic styles from the built-in toolkit themes because they are tied to the control type (TreeView in this case).  The only ugly workaround I found so far for this problem is to copy the styles from the Toolkit source code and reuse them in the application.

    Read the article

  • WPF properties memory management

    - by mrpyo
    I'm trying to build binding system similar to the one that is used in WPF and I ran into some memory leaking problems, so here comes my question - how is memory managed in WPF property system? From what I know in WPF values of DependencyProperties are stored in external containers - what I wanna know is how are they collected when DependencyObject dies? Simplest solution would be to store them is some weak reference dictionary - but here comes the main problem I ran into - when there is a listener on property that needs reference to its (this property) parent it holds it (the parent) alive (when value of weak reference dictionary points somewhere, even indirectly, to key - it can't be collected). How is it avoided in WPF without the need of using weak references everywhere?

    Read the article

  • WPF customer control and direct content support

    - by Mmarquee
    I am fairly new to WPF, and am a bit stuck, so any help would be appreciated. I am trying to write WPF custom control that encapsulates several elements of functionality that I already having working (i.e sorting, filtering, standard menus, etc.), but in a nice neat package to avoid repetition. Anyway I have created the custom control (based on control), and then have the following in the Generic.Xaml <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Controls.ListViewExtended"> <Style TargetType="{x:Type local:ListViewExtended}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ListViewExtended}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ListView> <ListView.View> <GridView> <!-- Content goes here --> </GridView> </ListView.View> </ListView> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> When I try to add GridViewColumns (or any control really), as below ... <elv:ListViewExtended> <GridView> <GridViewColumn Width="140" Header="Column 1" /> <GridViewColumn Width="140" Header="Column 2" /> <GridViewColumn Width="140" Header="Column 3" /> </GridView> </elv:ListViewExtended> I get the "... does not support direct content" error. I have created a dependancy property (again below) that allows the adding of GridView, but it still doesn't work. public static DependencyProperty GridViewProperty; public static string GridViewHeader(DependencyObject target) { return (string)target.GetValue(GridViewProperty); } public static void GridViewHeader(DependencyObject target, string value) { target.SetValue(GridViewProperty, value); } Thanks in advance

    Read the article

  • Silverlight 4 DataBinding: Binding to ObservableCollection<string> not working anymore

    - by Kurt
    Upgrading from SL3 - SL4. First problem: this throws a parser exception: <StackPanel Name={Binding} /> (same with x:Name) Collection is ObservableCollection<string>. Worked fine in SL3. So it seems that SL4 doen't allow binding to the Name property. Huh? So: changed to <StackPanel Tag={Binding} /> ... since I just need to ID the control in code behind. So here's the bug ('cuz this has got to be a bug!): In this frag, AllAvailableItems is an ObservableCollection<string>: <ItemsControl Name="lbItems" ItemsSource="{Binding AllAvailableItems}" Height="Auto" Width="Auto" BorderBrush="Transparent" BorderThickness="0" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="12,6,0,0"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <CheckBox Tag="{Binding}" Checked="ItemChecked_Click" Unchecked="ItemUnchecked_Click" Style="{StaticResource CheckBoxStyle}" Grid.Row="0"> <CheckBox.Content> <TextBlock Text="{Binding}" Style="{StaticResource FormLJustStyle}" /> </CheckBox.Content> </CheckBox> <StackPanel Tag="{Binding}" Orientation="Vertical" Grid.Row="1"> <configControls:ucLanguage /> <!-- simple user control --> </StackPanel> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> In the code behind, I use a recursive function to find the Dependency object with either the Name or Tag property provided: public static T FindVisualChildByName<T>(DependencyObject parent, string name, DependencyProperty propToUse) where T : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var child = VisualTreeHelper.GetChild(parent, i); string controlName = child.GetValue(propToUse) as string; if (controlName == name) { return child as T; } else { T result = FindVisualChildByName<T>(child, name, propToUse); if (result != null) return result; } } return null; } OK, get this: in the code behind, I can get the control that is ORDERED FIRST in the XAML! In other words, if I put the CheckBox first, I can retrieve the CheckBox, but no StackPanel. And vice-versa. This all worked fine in SL3. Any help, ideas ... ? Thanks - Kurt

    Read the article

  • Why won't this hit test fire a second time? wpf

    - by csciguy
    All, I have a main window that contains two custom objects (AnimatedCharacter). These objects are nothing but images. These images might contain transparent portions. One of these objects slightly overlaps the other object. There is a listener attached to the main window and is as follows. private void Window_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e) { Point pt = e.GetPosition((UIElement)sender); //store off the mouse pt hitPointMouse = pt; //clear the result list hitResultsSubList.Clear(); EllipseGeometry m_egHitArea = new EllipseGeometry(pt, 1, 1); VisualTreeHelper.HitTest(sender as Visual, HitTestFilterFuncNew, new HitTestResultCallback(HitTestCallback), new GeometryHitTestParameters(m_egHitArea)); //Check all sub items you have now hit if (hitResultsSubList.Count > 0) { CheckSubHitItems(hitResultsSubList); } } The idea is to filter out only a select group of items (called AnimatedCharacters). The hittest and filters are as follows public HitTestResultBehavior HitTestCallback(HitTestResult htrResult) { IntersectionDetail idDetail = ((GeometryHitTestResult)htrResult).IntersectionDetail; switch (idDetail) { case IntersectionDetail.FullyContains: return HitTestResultBehavior.Continue; case IntersectionDetail.Intersects: return HitTestResultBehavior.Continue; case IntersectionDetail.FullyInside: return HitTestResultBehavior.Continue; default: return HitTestResultBehavior.Stop; } } public HitTestFilterBehavior HitTestFilterFuncNew(DependencyObject potentialHitTestTarget) { if (potentialHitTestTarget.GetType() == typeof(AnimatedCharacter)) { hitResultsSubList.Add(potentialHitTestTarget as AnimatedCharacter); } return HitTestFilterBehavior.Continue; } This returns me back a list (called hitResultsSubList) that I attempt to then process further. I want to take everything in the hitResultsSubList and run a hit test on it again. This time, the hit test will be checking alpha levels on the particular animatedCharacter object. private void CheckSubHitItems(List<DependencyObject> hitResultsSub) { for(int i = 0; i<hitResultsSub.Count; i++) { hitResultsList.Clear(); AnimatedCharacter ac = hitResultsSub[i] as AnimatedCharacter; try { //DEBUGGER SKIPS THIS NEXT LINE EVERY SINGLE TIME. VisualTreeHelper.HitTest(ac, null, new HitTestResultCallback(hitCallBack), new PointHitTestParameters(hitPointMouse)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); } if (hitResultsList.Count > 0) { //do something here } } } Here is my problem now. The hit test in the second function (CheckSubHitItems) never gets called. There are definitely items (DependencyObjects of the type AnimatedCharacter) in the hitResultSub, but no matter what, the second hit test will not fire. I can walk the for loop fine, but when that line is hit, I get the following console statement. Step into: Stepping over non-user code 'System.MulticastDelegate.CtorClosed' No exceptions are thrown. Any help is appreciated.

    Read the article

  • How do I get the ListBox from a ListBoxItem?

    - by Shimmy
    Sub FindAncestor(Of TParent, reference As DependencyObject) As TParent 'find the parent ListBox container End Sub 'Usage Sub Handle(lbi As ListBoxItem) Dim lb = GetListBox(lbi) End Sub I have a button in a ListBoxItem datatemplate, I want in the handler of the button to access the parent ListBox (this is the way I want to access it, since it's all nested in other DataTemplates, ItemsControls and stuff).

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >