.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Post New Web Links

Binding Question How does one set datacontext to same class in XAML?

Posted By:      Posted Date: October 02, 2010    Points: 0   Category :WPF
 

I have a usercontrol with one button in it.  I want to set the text via a property getter setter using the INotifyPropertyChanged interface in code behind.  I can get it to work if I set the DATACONTEXT in code behind in the CTOR like this : DataContext = this;  Everything works perfect. 

But here's the problem.  If I try to do this in xaml by defining an XMLNS which points to the folder this usercontrol is in, and then attempt to reference it as a resouce like this <local:XXXXXX  <-------The XXXX which is the class name of this control can't be found?  Is that wierd?  Can't a resource be itself?  So that I can set the Datacontext in the XAML instead of code behind?  I've tried to bind to relative source self, but cannot set the property (Event when I attempted to created a dependency property).....  Just wondering how one sets up Datacontext to the same class? 


Javaman


View Complete Post


More Related Resource Links

Cannot set DataContext to a Class through XAML

  
Hi, I understand this has been answered several times as I browse this forum, however I can't get the various implementation examples to work within my code - i think i need help. Here's a perfectly working code: namespace TestStuff { public partial class Window1 : Window { class woot { int _bind = 50; public int Bind { get { return _bind; } set { _bind = value; } } } woot WOOT = new woot(); public Window1() { InitializeComponent(); mygrid.DataContext = WOOT; } } }   <Window x:Class="TestStuff.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Name="mygrid"> <Label Content="{Binding Path=Bind}"/> </Grid> </Window> What's the simplest way to set the DataContext of "myGrid" to WOOT, through XAML instead of using C#? Something like: <Grid DataContext="WOOT"> There are so many replies out there involving relativesource, objectdataprovider, dependency properties... however for some reason, I can't get any of them to work properly. I need to set the datacontext to the grid and not the window, since different grid

Simple data binding question

  
Newbie binding question here: is it possible to bind a control in XAML to a StaticResource by passing in the key via a data structure? Basically something like this: <TextBlock Text="{Binding ImageKey}" /> <Image Source="{StaticResource ResourceKey={Binding ImageKey}}" /> <-- doesn't work   The TextBlock binding on the first line works correctly, it extracts the key of the StaticResource from my data structure and displays it correctly. What I'm trying to do is get the Image control to bind to the StaticResource with that name (which happens to be a BitmapImage).      

Data binding without typing out xaml

  
Now I'm not stumped on getting data binding to work, I simply want to know how to utilize the window interfaces that visual studio 2010 comes with - as opposed to typing in XAML.  All I want to do is bind a font size property to an xml file within the project.   Here's what I do: After selecting the text box, in the properties panel, i go to the text category then click on the data-binding icon next to the font size field.  I then click on 'apply data binding', where a small panel pops up.  This is where I become stuck.  It seems like I need a path to the xml file, but I don't know how to add that in without typing in XAML.  I would assume that I would be able to add in a resource somewhere - kind of like windows forms allow me to do. I've never worked with WPF before, so I know it's something small/simple that i'm missing.  Any help would be appreciated. thanks, Phil

Custom markup extension or custom binding class?

  
Hey experts! I'm doing a project where I've encountered an issue I'd love some feedback on. I've created a custom Markup Extension called MyMarkupExtension, with two properties.  I can use it like below: <cc:DialogBorder Title="{local:MyMarkupExtension MyProperty='property value goes here', AnotherProperty='and another value here'}"> It works, and in 99% of the cases, it fits my needs perfectly.  In 1% of the cases, the values of MyProperty and AnotherProperty can not be set at design time, so I'd need some binding there. <cc:DialogBorder Title="{local:MyMarkupExtension MyProperty={Binding Path='SomePropertyOfTheViewModel'}, AnotherProperty='and another value here'}"> This presents my two questions (yes I did make only one post for 2 questions, bad karma...): 1. the binding inside my markup is not legal, after all, a binding can only be set on a DependencyProperty.  Is there any workaround which I could use for this problem at hand? In case there isnt... 2. I'm thinking about dropping the markup extension and creating a custom binding instead.  For this, I'd have to inherit from bindingbase, and so far I've read online that's one ____ of a nightmare.  Does anyone have some good code / examples on where to start? "The improbable we do, the impossible just takes

Changing datacontext gives binding errors

  
On the change of the datacontext (of a user control), I check the type of the datacontext. If required (in my case, the datacontext is of a specific type), I want to change the datacontext. As soon as I change the datacontext, the DataContext property is correctly updated. However, I still get binding errors that "Property 'x' is not found on type 'y'", where 'y' is the old datacontext type. Is there any specific steps I have to take to successfully update the datacontext (and the bindings) to the new datacontext object?Geert van Horrik - CatenaLogic Visit my blog: http://blog.catenalogic.com Looking for a way to deploy your updates to all your clients? Try Updater!

Data binding without typing out xaml

  
Now I'm not stumped on getting data binding to work, I simply want to know how to utilize the window interfaces that visual studio 2010 comes with - as opposed to typing in XAML.  All I want to do is bind a font size property to an xml file within the project.   Here's what I do: After selecting the text box, in the properties panel, i go to the text category then click on the data-binding icon next to the font size field.  I then click on 'apply data binding', where a small panel pops up.  This is where I become stuck.  It seems like I need a path to the xml file, but I don't know how to add that in without typing in XAML.  I would assume that I would be able to add in a resource somewhere - kind of like windows forms allow me to do. I've never worked with WPF before, so I know it's something small/simple that i'm missing.  Any help would be appreciated. thanks, Phil

Early Late binding & Polymorphism question

  
Hi,I read this online about early & late binding.. I don't understand (the example below) how it is, can anyone explain why?Early binding:: Properties and method can be identified by compile time.Example: dim rs as recordsetLate binnding: Properties and method can be identified by Run time.Example: dim obj as classnameset obj=new classnamePolymorphism:Also, why the reason they are said Method overloading & OverridingExample of Compile Time Polymorphism: Method OverloadingExample of Run Time Polymorphism: Method OverridingCan anyone explain the logic behind these two? Thanks in advanceThanks

Animation sample and basic XAML question.

  
I am trying to put into place the animation sample in http://msdn.microsoft.com/en-us/library/system.windows.media.animation.stringkeyframe.keytime.aspx It doesn't work. I have two questions. 1) The example lists both the XAML and the C# code. It doesn't seem that the two are tied together. In this example is the XAML and C# code just two ways of obtaining the same result? 2) When the Rectangle is constructed in the C# code the properties set and the delegate event 'Loaded' asssigned. How is this event triggered? Just for learning purposes I would like to have this rectangle move across the bounds of the application window when triggered and stop again under user control. I am not sure how to construct the restangle then have it tied to my main window. Thank you. Kevin

Some Useful Properties of Binding Class

  
When binding the UI control with the data source the Binding class has some useful properties.In this post we will look at them and use them in sample application. The properties which we are going to discuss in this post are the FallbackValue ,TargetNullValue, and StringFormat. Image 1 shows the output of the example code.

Another basic Data Binding question

  
3 days ago (thanks to Olaf) I was able to make progress with binding a data collection to a DataGrid. Since then I have searched the web in vain for a VB example to enable me to switch off the DataGrid AutoGenerateColumns and enter my own columns and appropriate Paths to the Collection’s properties.   The following code works fine but I can’t work out how to enter my own individual columns etc. Can anyone give me the syntax for an example of one column please?   Why is it so difficult to find VB examples of WPF demos etc? (Nearly everything is in C#.)   I have some experience in Access VB so have picked VB in trying to use WPF. I would be grateful for any links to VB WPF resources. Option Explicit On Option Strict On Imports System.Collections.ObjectModel Partial Public Class DataGrid_FilledFromCodeBehind Private _ocEng As ObservableCollection(Of EnPlayer) Public Property EngSqd() As ObservableCollection(Of EnPlayer) Get Return _ocEng End Get Set(ByVal value As ObservableCollection(Of EnPlayer)) _ocEng = value End Set End Property Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded _ocEng = New ObservableCollection(Of EnPlayer)() For i = 0 To 4 EngSqd.Add(New EnPlayer(ref(i), names(i), ages(i), bat(i))) Next Me.DataCon

Binding a custom type in XAML ?

  
Hi, I'd like to bind a property "myProperty" of type "MyType" in the text property of TextBlock : <TextBlock Text="{Binding myProperty, Mode=OneWay}" And I overrided the ctype operator to have conversion from "MyType" to String: Public Overloads Shared Narrowing Operator CType(ByVal v As MyType) As String ...................... End Operator But it seems not work! I get the ToString of "MyType" in result but not the return of CType operator. Is it normal ? Why ?   Thanks for your help.  

XAML Autoinsert Question

  
Hi, I hope this is the right place to ask, I did searches but could not find anything related to this inquiry.   I have a question about the "autocomplete" of XAML element attributes, specifically the double quotes.  How do I actually go "past" the end quote? For ex: If I have <SolidColorBrush Color="Green" /> and I type <SolidColorBrush Color= When I hit the "=" character it auto inserts "", which I'm okay with.  Then I type "Gree" and then type the close quotation and then it doesn't insert another end quote but simply takes me past the end quote after autocompleting Green   However, for attributes such as <Button Width= It also inserts the start/end quotes, however if I type 190 and then enter the end quote character, it inserts another quote character instead of taking me past the end quote, so I end up with <Button Width="190"" and then I need to fix it.   It wastes alot of time to move my hand to the arrow keys and then hit right instead of just letting me hit enter, or end quote to get past it.   To reiterate, when I type numbers that can't be autocompleted, is there something I can hit (other than right arrow) to get past the end quote?  If not, can I change auto insert so that the end quote doesn't show up? Thanks

Dynamically Assign Datagrid Column Binding from XAML

  

I am trying to build a generic user control that will serve as a quick list maintenance screen.

I have a base ViewModel that has two string properties IDColumnName and DisplayColumnName and then a collection of objects to be edited.  Inherited view models will be created for each object type that needs to be maintained.  The usercontrols datacontext is set to the viewmodel.

What I want to do is have the datagrid, who's itemssource is bound to the collection of objects in the viewmodel, have one column and have that one column bound to the property specified in the DisplayColumnName property of the viewmodel, and I'd like to do it all in XAML.  I've got the datagrids rowdetailstemplate being dynamically determined based on the object type but am struggling with dynamically setting which property the one column displays.


Binding a treeview to a LinqToSQL class...

  

Hi all,

I have a LinQtoSQL class which encapsulates a table with the following relationship:

Id (int)
Parent ID(int)
Name (string)

Here, the parent ID is the id of another row int he same table. So, the table could look like:

1, null, grandpa
2,1, mom
3,2,me
3,2,sis

What I want to do is the create a treeview that binds to the table so that it looks like this:

grandpa
    mom
        me
        sis

Also, I should be able to add or delete nodes/rows...

Any ideas on how to do this? Is this even possible without writing the code to do all the population and the edit etc?

 

thanks,

Jas

 


Question on a class that is reused

  

I have a generic class that just has the following:

    public class GenericMap
    {


        private int _Number_1 = 0,
                    _Number_2 = 0,
                    _Number_3 = 0,
                    _Number_4 = 0,
                    _Number_5 = 0,
                    _Number_6 = 0,
                    _Number_7 = 0,
                    _Number_8 = 0;
        private string _String_1 = string.Empty,
                       _String_2

Design Question - Child Class Reference

  

There has to be a better way to design the following:

public class Member {
  public int stateID {get; set;}

  public State state {
    get {
      if (this.stateID > 0) 
        state = State.GetByID(this.stateID);
    }
  }
}

public class State {
  public string name {get; set; }

  public static State GetByID(int id) {
    //populates state from db
  }
}


Now if I loop through a list of members and need to display the state name for each member and I call "myMember.State.name" - I'll get the name of the state but it costs me an extra query everytime I call that - even though some of the states may be the same.

Is there a way somehow keep some sort of cache of state name from the db for access?


Thanks.


Extending Page class in XAML and code-behind

  

I have several XAML "Page"s for which I would like to pull the facets that are in common together into a Page class extension I am calling ACPage. I must be missing some essential piece of knowledge, although I think I am pretty close. Can someone tell me what I am missing? I am learning C#, XAML, .NET, etc. all simultaneously.

I get the following warning:
Warning 1 'Al_Cr.PageWelcome.InitializeComponent()' hides inherited member 'Al_Cr.ACPage.InitializeComponent()'. Use the new keyword if hiding was intended. D:\Projects\Al Cr\Al Cr\Al Cr\obj\x86\Release\PageWelcome.g.cs 50 21 Al Cr

and this error:
Error 2 'Al_Cr.ACPage' cannot be the root of a XAML file because it was defined using XAML. Line 1 Position 15. D:\Projects\Al Cr\Al Cr\Al Cr\PageWelcome.xaml 1 15 Al Cr

The warning points to the auto-generated PageWelcome.InitializeComponent() function definition. The error points to the end of the bolded text, below.

My ACPage.xaml & ACPage.xaml.cs is defined thusly:

<Page x:Class="Al_Cr.ACPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="

Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend