Search Results

Search found 4490 results on 180 pages for 'binding'.

Page 2/180 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Metro: Declarative Data Binding

    - by Stephen.Walther
    The goal of this blog post is to describe how declarative data binding works in the WinJS library. In particular, you learn how to use both the data-win-bind and data-win-bindsource attributes. You also learn how to use calculated properties and converters to format the value of a property automatically when performing data binding. By taking advantage of WinJS data binding, you can use the Model-View-ViewModel (MVVM) pattern when building Metro style applications with JavaScript. By using the MVVM pattern, you can prevent your JavaScript code from spinning into chaos. The MVVM pattern provides you with a standard pattern for organizing your JavaScript code which results in a more maintainable application. Using Declarative Bindings You can use the data-win-bind attribute with any HTML element in a page. The data-win-bind attribute enables you to bind (associate) an attribute of an HTML element to the value of a property. Imagine, for example, that you want to create a product details page. You want to show a product object in a page. In that case, you can create the following HTML page to display the product details: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Application1</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- Application1 references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> </head> <body> <h1>Product Details</h1> <div class="field"> Product Name: <span data-win-bind="innerText:name"></span> </div> <div class="field"> Product Price: <span data-win-bind="innerText:price"></span> </div> <div class="field"> Product Picture: <br /> <img data-win-bind="src:photo;alt:name" /> </div> </body> </html> The HTML page above contains three data-win-bind attributes – one attribute for each product property displayed. You use the data-win-bind attribute to set properties of the HTML element associated with the data-win-attribute. The data-win-bind attribute takes a semicolon delimited list of element property names and data source property names: data-win-bind=”elementPropertyName:datasourcePropertyName; elementPropertyName:datasourcePropertyName;…” In the HTML page above, the first two data-win-bind attributes are used to set the values of the innerText property of the SPAN elements. The last data-win-bind attribute is used to set the values of the IMG element’s src and alt attributes. By the way, using data-win-bind attributes is perfectly valid HTML5. The HTML5 standard enables you to add custom attributes to an HTML document just as long as the custom attributes start with the prefix data-. So you can add custom attributes to an HTML5 document with names like data-stephen, data-funky, or data-rover-dog-is-hungry and your document will validate. The product object displayed in the page above with the data-win-bind attributes is created in the default.js file: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { var product = { name: "Tesla", price: 80000, photo: "/images/TeslaPhoto.png" }; WinJS.Binding.processAll(null, product); } }; app.start(); })(); In the code above, a product object is created with a name, price, and photo property. The WinJS.Binding.processAll() method is called to perform the actual binding (Don’t confuse WinJS.Binding.processAll() and WinJS.UI.processAll() – these are different methods). The first parameter passed to the processAll() method represents the root element for the binding. In other words, binding happens on this element and its child elements. If you provide the value null, then binding happens on the entire body of the document (document.body). The second parameter represents the data context. This is the object that has the properties which are displayed with the data-win-bind attributes. In the code above, the product object is passed as the data context parameter. Another word for data context is view model.  Creating Complex View Models In the previous section, we used the data-win-bind attribute to display the properties of a simple object: a single product. However, you can use binding with more complex view models including view models which represent multiple objects. For example, the view model in the following default.js file represents both a customer and a product object. Furthermore, the customer object has a nested address object: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { var viewModel = { customer: { firstName: "Fred", lastName: "Flintstone", address: { street: "1 Rocky Way", city: "Bedrock", country: "USA" } }, product: { name: "Bowling Ball", price: 34.55 } }; WinJS.Binding.processAll(null, viewModel); } }; app.start(); })(); The following page displays the customer (including the customer address) and the product. Notice that you can use dot notation to refer to child objects in a view model such as customer.address.street. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Application1</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- Application1 references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> </head> <body> <h1>Customer Details</h1> <div class="field"> First Name: <span data-win-bind="innerText:customer.firstName"></span> </div> <div class="field"> Last Name: <span data-win-bind="innerText:customer.lastName"></span> </div> <div class="field"> Address: <address> <span data-win-bind="innerText:customer.address.street"></span> <br /> <span data-win-bind="innerText:customer.address.city"></span> <br /> <span data-win-bind="innerText:customer.address.country"></span> </address> </div> <h1>Product</h1> <div class="field"> Name: <span data-win-bind="innerText:product.name"></span> </div> <div class="field"> Price: <span data-win-bind="innerText:product.price"></span> </div> </body> </html> A view model can be as complicated as you need and you can bind the view model to a view (an HTML document) by using declarative bindings. Creating Calculated Properties You might want to modify a property before displaying the property. For example, you might want to format the product price property before displaying the property. You don’t want to display the raw product price “80000”. Instead, you want to display the formatted price “$80,000”. You also might need to combine multiple properties. For example, you might need to display the customer full name by combining the values of the customer first and last name properties. In these situations, it is tempting to call a function when performing binding. For example, you could create a function named fullName() which concatenates the customer first and last name. Unfortunately, the WinJS library does not support the following syntax: <span data-win-bind=”innerText:fullName()”></span> Instead, in these situations, you should create a new property in your view model that has a getter. For example, the customer object in the following default.js file includes a property named fullName which combines the values of the firstName and lastName properties: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { var customer = { firstName: "Fred", lastName: "Flintstone", get fullName() { return this.firstName + " " + this.lastName; } }; WinJS.Binding.processAll(null, customer); } }; app.start(); })(); The customer object has a firstName, lastName, and fullName property. Notice that the fullName property is defined with a getter function. When you read the fullName property, the values of the firstName and lastName properties are concatenated and returned. The following HTML page displays the fullName property in an H1 element. You can use the fullName property in a data-win-bind attribute in exactly the same way as any other property. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Application1</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- Application1 references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> </head> <body> <h1 data-win-bind="innerText:fullName"></h1> <div class="field"> First Name: <span data-win-bind="innerText:firstName"></span> </div> <div class="field"> Last Name: <span data-win-bind="innerText:lastName"></span> </div> </body> </html> Creating a Converter In the previous section, you learned how to format the value of a property by creating a property with a getter. This approach makes sense when the formatting logic is specific to a particular view model. If, on the other hand, you need to perform the same type of formatting for multiple view models then it makes more sense to create a converter function. A converter function is a function which you can apply whenever you are using the data-win-bind attribute. Imagine, for example, that you want to create a general function for displaying dates. You always want to display dates using a short format such as 12/25/1988. The following JavaScript file – named converters.js – contains a shortDate() converter: (function (WinJS) { var shortDate = WinJS.Binding.converter(function (date) { return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear(); }); // Export shortDate WinJS.Namespace.define("MyApp.Converters", { shortDate: shortDate }); })(WinJS); The file above uses the Module Pattern, a pattern which is used through the WinJS library. To learn more about the Module Pattern, see my blog entry on namespaces and modules: http://stephenwalther.com/blog/archive/2012/02/22/windows-web-applications-namespaces-and-modules.aspx The file contains the definition for a converter function named shortDate(). This function converts a JavaScript date object into a short date string such as 12/1/1988. The converter function is created with the help of the WinJS.Binding.converter() method. This method takes a normal function and converts it into a converter function. Finally, the shortDate() converter is added to the MyApp.Converters namespace. You can call the shortDate() function by calling MyApp.Converters.shortDate(). The default.js file contains the customer object that we want to bind. Notice that the customer object has a firstName, lastName, and birthday property. We will use our new shortDate() converter when displaying the customer birthday property: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { var customer = { firstName: "Fred", lastName: "Flintstone", birthday: new Date("12/1/1988") }; WinJS.Binding.processAll(null, customer); } }; app.start(); })(); We actually use our shortDate converter in the HTML document. The following HTML document displays all of the customer properties: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Application1</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- Application1 references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> <script type="text/javascript" src="js/converters.js"></script> </head> <body> <h1>Customer Details</h1> <div class="field"> First Name: <span data-win-bind="innerText:firstName"></span> </div> <div class="field"> Last Name: <span data-win-bind="innerText:lastName"></span> </div> <div class="field"> Birthday: <span data-win-bind="innerText:birthday MyApp.Converters.shortDate"></span> </div> </body> </html> Notice the data-win-bind attribute used to display the birthday property. It looks like this: <span data-win-bind="innerText:birthday MyApp.Converters.shortDate"></span> The shortDate converter is applied to the birthday property when the birthday property is bound to the SPAN element’s innerText property. Using data-win-bindsource Normally, you pass the view model (the data context) which you want to use with the data-win-bind attributes in a page by passing the view model to the WinJS.Binding.processAll() method like this: WinJS.Binding.processAll(null, viewModel); As an alternative, you can specify the view model declaratively in your markup by using the data-win-datasource attribute. For example, the following default.js script exposes a view model with the fully-qualified name of MyWinWebApp.viewModel: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { // Create view model var viewModel = { customer: { firstName: "Fred", lastName: "Flintstone" }, product: { name: "Bowling Ball", price: 12.99 } }; // Export view model to be seen by universe WinJS.Namespace.define("MyWinWebApp", { viewModel: viewModel }); // Process data-win-bind attributes WinJS.Binding.processAll(); } }; app.start(); })(); In the code above, a view model which represents a customer and a product is exposed as MyWinWebApp.viewModel. The following HTML page illustrates how you can use the data-win-bindsource attribute to bind to this view model: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Application1</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- Application1 references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> </head> <body> <h1>Customer Details</h1> <div data-win-bindsource="MyWinWebApp.viewModel.customer"> <div class="field"> First Name: <span data-win-bind="innerText:firstName"></span> </div> <div class="field"> Last Name: <span data-win-bind="innerText:lastName"></span> </div> </div> <h1>Product</h1> <div data-win-bindsource="MyWinWebApp.viewModel.product"> <div class="field"> Name: <span data-win-bind="innerText:name"></span> </div> <div class="field"> Price: <span data-win-bind="innerText:price"></span> </div> </div> </body> </html> The data-win-bindsource attribute is used twice in the page above: it is used with the DIV element which contains the customer details and it is used with the DIV element which contains the product details. If an element has a data-win-bindsource attribute then all of the child elements of that element are affected. The data-win-bind attributes of all of the child elements are bound to the data source represented by the data-win-bindsource attribute. Summary The focus of this blog entry was data binding using the WinJS library. You learned how to use the data-win-bind attribute to bind the properties of an HTML element to a view model. We also discussed several advanced features of data binding. We examined how to create calculated properties by including a property with a getter in your view model. We also discussed how you can create a converter function to format the value of a view model property when binding the property. Finally, you learned how to use the data-win-bindsource attribute to specify a view model declaratively.

    Read the article

  • Data binding in web UI frameworks, what's the deal?

    - by c-smile
    I believe that most of modern Web frameworks that pretend to be MVC ones also has a notion of data binding in one form or another. Examples: AngularJS, EmberJS, KnockoutJS, etc. I am assuming that "data binding" is a declarative definition (oxymoron, no?) of live link between data (a.k.a. model) and its representation (a.k.a. view). With some transformers in between (a.k.a. controllers). I understand why declarativeness is kind of appealing but also understand that as usual it comes with the price. In particular: 1. Live binding is quite heavy, either with dirty watch (high CPU consumption) or with Object.observe() (high memory consumption with high CPU load in some scenarios). 2. There is a "frame" part in the framework word, means there are some boundaries/limits that can be hard to overcome if you need slightly more than it was designed for. Quite usual time split: 90% of features are made in 10% of project time. But 10% rest take 90% of project time. I suspect (a.k.a. educated guess) that those MVC things are not helping to implement more functionality in less time... If so their usage motivation is not quite clear. As an example: last week wanted to find virtual list idea/solution. Found one in vanilla JavaScript that is 120 LOC. Implementation of the same but in AngualrJS is about 420 LOC. Most of the code there seems like a fight with the framework itself... So is my question: what benefits that MVC stuff or data binding give us? Is it just a buzzword popular among project managers or they give us something useful. If later one then what exactly?

    Read the article

  • Wpf binding to a function

    - by carlopenid
    I've a created a simple scrollviewer (pnlDayScroller) and want to have a separate horizontal scrollbar (associated scroller) to do the horizontal scrolling. All works with the below code accept I need to bind the visibility of the associated scroller. I can't simply bind this to the visibility property of the horizontal template part of the scroll viewer as I've set this to be always hidden. The only way I can think to do this is to bind the visibility of the associated scroller to a function such that If associatedScroller.scrollableWidth > 0 then associatedScroller.visibility = visibility.visible else associatedScroller.visibility = visibility.collapsed end if Is this possible to do and if so how do I do it? Private Sub pnlDayScroller_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles pnlDayScroller.Loaded Dim binViewport, binMax, binMin, binSChange, binLChange As Binding Dim horizontalScrollBar As Primitives.ScrollBar = CType(pnlDayScroller.Template.FindName("PART_HorizontalScrollBar", pnlDayScroller), Primitives.ScrollBar) binViewport = New Binding("ViewportSize") binViewport.Mode = BindingMode.OneWay binViewport.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.ViewportSizeProperty, binViewport) binMax = New Binding("Maximum") binMax.Mode = BindingMode.OneWay binMax.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.MaximumProperty, binMax) binMin = New Binding("Minimum") binMin.Mode = BindingMode.OneWay binMin.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.MinimumProperty, binMin) binSChange = New Binding("SmallChange") binSChange.Mode = BindingMode.OneWay binSChange.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.SmallChangeProperty, binSChange) binLChange = New Binding("LargeChange") binLChange.Mode = BindingMode.OneWay binLChange.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.LargeChangeProperty, binLChange) End Sub Private Sub associatedScroller_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of Double)) Handles associatedScroller.ValueChanged pnlDayScroller.ScrollToHorizontalOffset(e.NewValue) end sub FOLLOW UP (thanks to JustABill) : I've add this code into the pnlDayScroller sub above (I've discovered scrollableWidth is a property of scrollviewer not scrollbar, but the maximum property gives a result I can use instead) binVisibility = New Binding("Maximum") binVisibility.Mode = BindingMode.OneWay binVisibility.Source = horizontalScrollBar binVisibility.Converter = New ScrollableConverter associatedScroller.SetBinding(Primitives.ScrollBar.VisibilityProperty, binVisibility) and I've created this class Public Class ScrollableConverter Implements IValueConverter Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert Dim dblMaximum As Double If targetType IsNot GetType(Visibility) Then Throw New InvalidOperationException("The target must be a visibility") Else dblMaximum = CType(value, Double) Debug.WriteLine("Value of double is " & dblMaximum) If dblMaximum > 0 Then Return Visibility.Visible Else Return Visibility.Collapsed End If End If End Function Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack Throw New NotSupportedException() End Function End Class And the problem is resolved.

    Read the article

  • WPF binding to a boolean on a control

    - by Jose
    I'm wondering if someone has a simple succinct solution to binding to a dependency property that needs to be the converse of the property. Here's an example I have a textbox that is disabled based on a property in the datacontext e.g.: <TextBox IsEnabled={Binding CanEdit} Text={Binding MyText}/> The requirement changes and I want to make it ReadOnly instead of disabled, so without changing my ViewModel I could do this: In the UserControl resources: <UserControl.Resources> <m:NotConverter x:Key="NotConverter"/> </UserControl.Resources> And then change the TextBox to: <TextBox IsReadOnly={Binding CanEdit,Converter={StaticResource NotConverter}} Text={Binding MyText}/> Which I personally think is EXTREMELY verbose I would love to be able to just do this(notice the !): <TextBox IsReadOnly={Binding !CanEdit} Text={Binding MyText}/> But alas, that is not an option that I know of. I can think of two options. Create an attached property IsNotReadOnly to FrameworkElement(?) and bind to that property If I change my ViewModel then I could add a property CanEdit and another CannotEdit which I would be kind of embarrassed of because I believe it adds an irrelevant property to a class, which I don't think is a good practice. The main reason for the question is that in my project the above isn't just for one control, so trying to keep my project as DRY as possible and readable I am throwing this out to anyone feeling my pain and has come up with a solution :)

    Read the article

  • Custom binding with WCF

    - by user67240
    I have a wcf service where i have to implement the call backs and also i need to host the wcf service on the IIS 6.0, since IIS6.0 doesnot support the net.tcp binding, i decided to go for the custom binding. The reasons for going for custom binding is that the service is accessed by different clients in different timezones. Using custom binding i can set the allowed clock skew time to other values other than the default one. I have problem making the custom binding work for me. here is the server config file <bindings> <customBinding> <binding name="pscNetBinding" openTimeout="00:10:00"> <reliableSession acknowledgementInterval="00:00:00.2000000" flowControlEnabled="true" inactivityTimeout="23:59:59" maxPendingChannels="128" maxRetryCount="8" maxTransferWindowSize="128" ordered="true" /> <compositeDuplex /> <oneWay maxAcceptedChannels="128" packetRoutable="false"> <channelPoolSettings idleTimeout="00:10:00" leaseTimeout="00:10:00" maxOutboundChannelsPerEndpoint="10" /> </oneWay> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </textMessageEncoding> <httpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="2147483647" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true"/> </binding> </customBinding> </bindings> <services> <service name="SchneiderElectric.PSCNet.Server.Services.PSCNetWCFService" behaviorConfiguration="Behaviors1"> <host> <baseAddresses> <add baseAddress ="http://10.155.18.18:2000/PSCNet"/> </baseAddresses> </host> <endpoint address="" binding="customBinding" bindingConfiguration="pscNetBinding" contract="SchneiderElectric.PSCNet.Server.Contracts.IPSCNetWCFService"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Behaviors1"> <serviceMetadata httpGetEnabled = "true"/> <!--<serviceThrottling maxConcurrentCalls="2048" maxConcurrentSessions="2048" maxConcurrentInstances="2048" /> <dataContractSerializer maxItemsInObjectGraph="2147483647" />--> </behavior> </serviceBehaviors> </behaviors> and here the client config file <bindings> <customBinding> <binding name="pscNetBinding" openTimeout="00:10:00"> <reliableSession acknowledgementInterval="00:00:00.2000000" flowControlEnabled="true" inactivityTimeout="23:59:59" maxPendingChannels="128" maxRetryCount="8" maxTransferWindowSize="128" ordered="true" /> <compositeDuplex /> <oneWay maxAcceptedChannels="128" packetRoutable="false"> <channelPoolSettings idleTimeout="00:10:00" leaseTimeout="00:10:00" maxOutboundChannelsPerEndpoint="10" /> </oneWay> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" writeEncoding="utf-8" > <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </textMessageEncoding > <httpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="2147483647" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" /> </binding> </customBinding> </bindings> <client> <endpoint address="http://10.155.18.18:2000/PSCNet" binding="customBinding" bindingConfiguration="pscNetBinding" contract="PSCNetWCFService.IPSCNetWCFService" name="pscNetBinding" /> </client> if i use the server and client on the same machine everything works fine. But as soon as i run the server and client on different machine i get the following error "Could not connect to http://10.155.18.198:9000/e60ba5b3-f979-4922-b9f8-c820caaa04c2. TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.155.18.198:9000." Can anyone in the community help me in this regard.

    Read the article

  • Silverlight 3 Binding to the Current Item in a Collection

    - by rasx
    The Binding syntax, {Binding /}, works in WPF but does not work at all in Silverlight 3: <ContentControl Content="{Binding MyCollection}"> <ContentControl.ContentTemplate> <DataTemplate> <ContentControl Content="{Binding /}" /> </DataTemplate> </ContentControl.ContentTemplate> </ContentControl> What's the way to approach this in Silverlight?

    Read the article

  • What does binding mean exactly?

    - by Lily
    I always see people mention that "Python binding" and "C Sharp binding" etc. when I am actually using their C++ libraries. What does binding mean? If the library is written in C, and does Python binding means that they use SWIG kind of tool to mock a Python interface? Newbie in this field, and any suggestion will be welcomed.

    Read the article

  • ASP.NET MVC Binding - Duplicated Messages

    - by Rodrigo Gama
    I'm using ASP.NET MVC Binding Framework. Let's say I have a class Item, that has a mandatory field Id. I am binding a List, and do not want one error message for each element in this list. If more then one error happen when binding the Id field, I want only one message to be added to ModelState and shown to the user. In one sentence: Is there a way to avoid duplicated messages using ASP.NET MVC Binding Framework?

    Read the article

  • SelectedItem in ListView binding

    - by Matt
    I'm new in wfp. In my sample application I'm using a ListView to display contents of property. I don't know how to bind SelectedItem in ListView to property and then bind to TextBlock. Window.xaml <Window x:Class="Exec.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Main window" Height="446" Width="475" > <Grid> <ListView Name="ListViewPersonDetails" Margin="15,12,29,196" ItemsSource="{Binding Persons}" SelectedItem="{Binding CurrentSelectedPerson}"> <ListView.View> <GridView> <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding FstNamePerson}"/> <GridViewColumn Header="LastName" DisplayMemberBinding="{Binding SndNamePerson}"/> <GridViewColumn Header="Address" DisplayMemberBinding="{Binding AdressPerson}"/> </GridView> </ListView.View> </ListView> <TextBlock Height="23" Name="textFirstNameBlock" FontSize="12" Margin="97,240,155,144"> <Run Text="Name: " /> <Run Text="{Binding CurrentSelectedPerson.FstNamePerson}" FontWeight="Bold" /> </TextBlock> <TextBlock Height="23" Name="textLastNameBlock" FontSize="12" Margin="97,263,155,121"> <Run Text="Branch: " /> <Run Text="{Binding CurrentSelectedPerson.SndNamePerson}" FontWeight="Bold" /> </TextBlock> <TextBlock Height="23" Name="textAddressBlock" FontSize="12" Margin="0,281,155,103" HorizontalAlignment="Right" Width="138"> <Run Text="City: " /> <Run Text="{Binding CurrentSelectedPerson.AdressPerson}" FontWeight="Bold" /> </TextBlock> </Grid> </Window> MainWindow.xaml.cs Tman manager = new Tman(); private List<Person> persons; public List<Person> Persons { get { return this.persons; } set { if (value != null) { this.persons = value; this.NotifyPropertyChanged("Data"); } } } private Person currentSelectedPerson; public Person CurrentSelectedPerson { get { return currentSelectedPerson; } set { this.currentSelectedPerson = value; this.NotifyPropertyChanged("CurrentSelectedItem"); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { var handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } private void Window_Loaded(object sender, RoutedEventArgs e){ ListViewPersonDetails.ItemsSource= manager.GetPersons(); } Person.cs class Person { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } Thanks for any help.

    Read the article

  • WPF - Binding a variable in an already bound ListBox?

    - by Corey Ogburn
    I really don't know how to title this question, but I need some help with binding to a ListBox. I have an object, that contains (among other information) 2 properties that need to be bound in one ListBox. One of these is an ObservableCollection of objects, called Layers, and the other property holds an enum value of either Point, Line or Polygon, called SpatialType. These are to act as a legend to a map application. I have bound Layers to a ListBox, no problem, but inside the ListBox.ItemTemplate, I need to bind the single variable SpatialType to every Item in the ListBox. The problem I'm running into is that when I try to bind while inside the ListBox, the only variables I have access to are the properties of each Layer and I can't access any properties of the original bound class that holds the Layers (and the needed SpatialType property). What can I do to get that piece of information bound inside the ItemTemplate without messing up a good MVVM architecture?

    Read the article

  • Custom CheckBox in WPF DataGrid does not update binding

    - by Pakman
    In my Visual Studio 2010 WPF application, I have the following (simplified) style: <Style x:Key="MyStyle" TargetType="{x:Type CheckBox}"> <Setter Property="Background" Value="Blue" /> </Style> If I use it as the ElementStyle AND EditingElementStyle in my DataGridCheckBoxColumn: <DataGridCheckBoxColumn Binding="{Binding IsEnabled}" ElementStyle="{StaticResource MyStyle}" EditingElementStyle="{StaticResource MyStyle}" /> Then my binding, IsEnabled, does not toggle when I check/uncheck a row's checkbox. If I remove either ElementStyle, EditingElementStyle, or both, then the binding updates no problem. Why is this?! Also, I tried to work around the problem using the following code: <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox IsChecked="{Binding IsEnabled}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> However, the problem remains.

    Read the article

  • WPF Binding to DataRow Columns

    - by Trindaz
    Hi, I've taken some sample code from http://sweux.com/blogs/smoura/index.php/wpf/2009/06/15/wpf-toolkit-datagrid-part-iv-templatecolumns-and-row-grouping/ that provides grouping of data in a WPF DataGrid. I'm modifying the example to use a DataTable instead of a Collection of entities. My problem is in translating a binding declaration {Binding Parent.IsExpanded}, which works fine where Parent is a reference to an entity that has the IsExpanded attribute, to something that will work for my weakly typed DataTable, where Parent is the name of a column and references another DataRow in the same DataTable. I've tried declarations like {Binding Parent.Items[IsExpanded]} and {Binding Parent("IsExpanded")} but none of these seem to work. How can I create a binding to the IsExpanded column of the DataRow Parent in my DataTable? Thanks in advance, Dave

    Read the article

  • Winforms - a strange problem a with simple binding

    - by Adi Barda
    Hi Guys, It's hard for me to clearly describe my problem but I'll try. I have a UserControl1 which contains UserControl2 which contains several WinForms controls (most of them DevExpress). I do simple binding to these controls to my datatable fields. So far everything works fine. When I move the focus to a record in the table (by navigating in a grid rows for example) the binding works great, the concurrenmcy manager moves the cursor and everything reflects right in the bounded controls. The problem starts when I add new user UserControl3 above UserControl2 and make UserControl2.Visible = false. Now UserControl3 is shown and UserControl2 exists but not shown. Now when I set UserControl2.Visible = true to show it again the simple binding stops working! I navigate in the grid but either the ConcurrencyManager stops working or the simple binding becomes disconnected. My question: Are there any known issues/ best practices with the binding & concurrency manager? Thanks a lot, Adi Barda

    Read the article

  • Element binding in Silverlight

    - by Matt
    Where can I find some good documentation on data/element binding? My Google searches haven't turned much up. I had a custom class with two properties named Text and Value. When I tried binding a list to a listbox it wouldn't work. By chance I modifed my datatemplate from this <TextBox Text="{Binding Text}"></TextBox> to this <TextBox Text="{Binding Path=Text}"></TextBox> and then everything worked great. I need some indepth documenation/samples to data/element binding. I don't understand why some examples have the path set whereas others do not. A full explanation of this, and all other nice to know tips would be much appreciated.

    Read the article

  • Shorter Binding expression with validation

    - by Andrii V
    Hi, I'm repeating same binding parameters for every textbox and they're quite long strings (which is not good for many reasons). And I'm wondering if there's a way to make them shorter? For instance all my controls on forms are using the following binding template: Text="{Binding SourceProperty, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" I'd would like to have something shorter that ideally will take SourceProperty as parameter. Possbly like this: Text="{MyBinding SourceProperty}" or Text="{Binding SourceProperty, Params=MyParams}" One possible option would be to inherit from Binding and create new markup extension. Did someone tried this? Any other ideas how to make these repetetive bindings look better?

    Read the article

  • Binding expression failing.

    - by Rohit Kandhal
    My output window is flooded with binding expression failures like : "Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.CurrentActivationObjectType; DataItem=null; target element is 'StackPanel' (Name=''); target property is 'NoTarget' (type 'Object')" and similar binding issues. Also i found that these failure occurs only when the screen loads (i.e. first time) No failures there after. I've checked the binding it is fine . Binding :

    Read the article

  • WPF - Correct Syntax for Using Coverter with Current Binding

    - by Andy T
    Hi, I have a collection of hex strings that represent colours and I am binding a combobox's ItemsSource to that collection. The combobox items are templated to have a filled rectangle with the relevant colour. I therefore need to use a converter to convert the hex value to a string. Easy enough. However, Blend is telling me that this syntax is incorrect in my XAML: Fill="{Binding, Converter={StaticResource StringToBrush}}" Apparently, I can't use a converter against plain old 'Binding'. Blend says that something like this is syntactically correct: Fill="{Binding Value, Converter={StaticResource StringToBrush}}" ...However that obviously doesn't work. I'm not quite au fait with binding syntax yet, so obviously I'm getting it wrong. Can anyone advise the correct syntax to achieve what I'm trying to do (convert my bound String using the coverter StringToBrush)? Thanks in advance! AT

    Read the article

  • Why doesn't my binding update whenever EditingElementStyle AND ElementStyle are set to a custom styl

    - by Pakman
    In my Visual Studio 2010 WPF application, I have the following (simplified) style: <Style x:Key="MyStyle" TargetType="{x:Type CheckBox}"> <Setter Property="Background" Value="Blue" /> </Style> If I use it as the ElementStyle AND EditingElementStyle in my DataGridCheckBoxColumn: <DataGridCheckBoxColumn Binding="{Binding IsEnabled}" ElementStyle="{StaticResource MyStyle}" EditingElementStyle="{StaticResource MyStyle}" /> Then my binding, IsEnabled, does not toggle when I check/uncheck a row's checkbox. If I remove either ElementStyle, EditingElementStyle, or both, then the binding updates no problem. Why is this?! Note: sometimes clicking around will produce an update to the binding (detected via debugging) - this is not the same as clicking another row to "commit" the value, though! Thanks!

    Read the article

  • Binding "Text-Property" of a derived textbox to another textbox doesn´t work

    - by Jehof
    Hello, i have a class 'MyTextBox' that derives from the default TextBox in Silverlight. This class currently contains no additional code. I set up a binding in xaml to bind the Text-Property of MyTextbox to another Textbox to reflect the input made in the Textbox. The effect is that MyTextBox doesn´t update and not display the text of the other Textbox. Additional i made an equal binding for a normal Textbox. And this works. Here´s the XAML for the bindings. <UserControl x:Class="Silverlight.Sample.Dummy" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:Sample" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <StackPanel x:Name="LayoutRoot" Background="White"> <TextBox Height="23" x:Name="textBox2" Width="120" /> <TextBox Text="{Binding ElementName=textBox2, Path=Text, Mode=TwoWay}" Width="120" /> <my:NumberTextBox Width="120" Text="{Binding ElementName=textBox2, Path=Text, Mode=OneWay}" /> </StackPanel> Is there something special to set for binding, when i derive from a control. PS: I tried a binding to a dummy object with INotifyPropertyChanged and set it as DataContext for the existing Textboxes. This test works as expected and my derived textbox gets updated.

    Read the article

  • WPF ComboBox binding

    - by Budda
    Here is peace of the XAML code from my page: <ComboBox Grid.Row="2" Grid.Column="1" Name="Player2" MinWidth="50" ItemsSource="{Binding PlayersTest}" DisplayMemberPath="ShortName"> custom object is binded to the page data context: page.DataContext = new SquadViewModel(); Here is part the source code of 'SquadViewModel' class: public class SquadViewModel { public SquadViewModel() { PlayersTest = new ObservableCollection<SostavPlayerData>(); PlayersTest.Add(new SostavPlayerData { ShortName = "A. Sereda", }); PlayersTest.Add(new SostavPlayerData { ShortName = "D. Sereda", }); } public readonly ObservableCollection<SostavPlayerData> PlayersTest; public string TestText { get { return "Binding works perfectly!"; } } } As a result ComboBox should display a list of objects, but it is empty. Do you know why and how to get this list? Thank you. P.S. I've tried another XAML markup <ComboBox Grid.Row="1" Grid.Column="1" Name="Player1" MinWidth="50" ItemsSource="{Binding PlayersTest}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding ShortName}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> It doesn't work also, but binding to simple text block: <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding TestText}"/> Works perfectly.

    Read the article

  • Binding problem in C# wpf

    - by Cinaird
    I have a problem whit binding in wpf i have a textbox where i can do some input, then i try to bind the textinput to a custom usercontrol. This work for the usercontrol within RowDetailsTemplate but not in the CellTemplate. For each object in the CellTemplate i get this error output: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=ScaleTextBox'. BindingExpression:Path=Text; DataItem=null; target element is 'Chart' (Name=''); target property is 'MaxValue' (type 'Int32') My code looks like this: XAML <ToolBarTray ToolBarTray.IsLocked="True" DockPanel.Dock="Top" Height="25"> <ToolBar Name="ButtonBar" > <TextBox Height="23" Name="ScaleTextBox" Width="120" Text="400"/> </ToolBar> </ToolBarTray> <DataGrid ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False" IsReadOnly="True" RowHeight="25" RowDetailsVisibilityMode="VisibleWhenSelected"> <DataGrid.RowDetailsTemplate> <DataTemplate> <StackPanel Orientation="Vertical" > <my:UserControl ItemsSource="{Binding Path=Samples}" MaxValue="{Binding ElementName=ScaleTextBox, Path=Text}"/>--> </StackPanel> </DataTemplate> </DataGrid.RowDetailsTemplate> <DataGrid.Columns> <DataGridTemplateColumn MinWidth="150" Header="Chart" > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <my:UserControl ItemsSource="{Binding Path=Samples}" MaxValue="{Binding ElementName=ScaleTextBox, Path=Text}"/><!-- this is the problem --> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> C# public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(int), typeof(PingChart), new FrameworkPropertyMetadata(MaxValuePropertyChanged)); private static void MaxValuePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { Console.WriteLine(e.NewValue); } What do i do wrong?

    Read the article

  • Resolving harmless binding errors in WPF II : 2 approaches for removing data binding errors due to heterogeneous types in a hierarchical view

    - by akjoshi
    This is a continuation post to my previous post Resolving harmless binding errors in WPF in which I talked about various ways of  resolving different binding errors etc. I recently came across another situation in which we get these binding errors and how they can be resolved. Problem: If you have a tree with 2 types of items in it and you use different DataTypes for each of them, then you will get binding errors because of missing Properties in either one of the item. In our case we had binding...(read more)

    Read the article

  • WPF: Setting DataContext of a UserControl with Binding not working in XAML

    - by Grant Crofton
    Hi, I'm trying to get my first WPF app working using MVVM, and I've hit a little binding problem. The setup is that I have a view & viewModel which holds User details (the parent), and to try and keep things simple I've put a section of that view into a separate view & viewModel (the child). The child view is defined as a UserControl. The issue I'm having is how to set the DataContext of the child view (the UserControl). My parent ViewModel has a property which exposes the child ViewModel, like so: class ParentViewModel: INotifyPropertyChanged { public ChildViewModel childViewModel { get; set; } //... } In the XAML for my parent view (which has it's DataContext set to the ParentViewModel), I try to set the DataContext of the child view as follows: <views:ChildView x:Name="ChildView" DataContext="{Binding childViewModel}"/> However, this doesn't work. The DataContext of the child view is set to the same DataContext as the parent view (i.e. the ParentViewModel), as if I wasn't setting it at all. I also tried setting the DataContext in the child view itself, which also doesn't work: <UserControl x:Class="DietRecorder.Client.View.ChildView" DataContext="childViewModel" I have found a couple of ways around this. In the child view, I can bind everything by including the ChildViewModel in the path: <SomeControl Visibility="{Binding Path=childViewModel.IsVisible}"> but I don't want the child view to have this level of awareness of the hierarchy. Setting the DataContext in code also works - however, I have to do this after showing the parent view, otherwise the DataContext just gets overwritten when I call Show(): parentView.Show(); parentView.ChildView.DataContext = parentViewModel.childViewModel; This code also makes me feel uneasy, what with the LOD violation and all. It's just the DataContext that seems to be the problem - I can bind other things in the child, for example I tried binding the FontSize to an int property just to test it: <views:ChildView x:Name="ChildView" FontSize="{Binding Path=someVal}"/> And that works fine. But I'm sure binding the DataContext should work - I've seen similar examples of this kind of thing. Have I missed something obvious here? Is there a reason this won't work? Is there a spelling mistake somewhere? (I renamed things for your benefit so you won't be able to help me there anyway). Any thoughts welcome. Thanks, Grant

    Read the article

  • Silverlight data binding to parent user control's properties with using MVVM in both controls

    - by MagicMax
    Hello! I have two UserControls ("UserControlParentView" and "UserControlChildView") with MVVM pattern implemented in both controls. Parent control is a container for Child control and child control's property should be updated by data binding from Parent control in order to show/hide some check box inside Child control. Parent Control Description UserControlParentViewModel has property: private bool isShowCheckbox = false; public bool IsShowCheckbox { get { return isShowCheckbox; } set { isShowCheckbox = value; NotifyPropertyChanged("IsShowCheckbox"); } } UserControlParentViewModel - how I set DataContext of Parent control: public UserControlParentView() { InitializeComponent(); this.DataContext = new UserControlParentViewModel(); } UserControlParentView contains toggle button (in XAML), bound to UserControlParentViewModel's property IsShowCheckbox <ToggleButton Grid.Column="1" IsChecked="{Binding IsShowCheckbox, Mode=TwoWay}"></ToggleButton> Also Parent control contains instance of child element (somewhere in XAML) <local:UserControlChildView IsCheckBoxVisible="{Binding IsShowCheckbox}" ></local:UserControlChildView> so property in child control should be updated when user togggle/untoggle button. Child control contains Boolean property to be updated from parent control, but nothing happened! Breakpoint never fired! Property in UserControlChildView that should be updated from Parent control (here I plan to make chechBox visible/hidden in code behind): public bool IsCheckBoxVisible { get { return (bool)GetValue(IsCheckBoxVisibleProperty); } set { SetValue(IsCheckBoxVisibleProperty, value); } } // Using a DependencyProperty as the backing store for IsCheckBoxVisible. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCheckBoxVisibleProperty = DependencyProperty.Register("IsCheckBoxVisible", typeof(bool), typeof(TopMenuButton), new PropertyMetadata(false)); So the question is - what I'm doing wrong? Why child's property is never updated? BTW - there is no any binding error warnings in Output window...

    Read the article

  • Binding Listbox ItemsSource to property of ViewModel in DataContext in WPF

    - by joshperry
    I have a simple ViewModel like: public class MainViewModel { public MainViewModel() { // Fill collection from DB here... } public ObservableCollection<Projects> ProjectList { get; set; } } I set the window's DataContext to a new instance of that ViewModel in the constructor: public MainWindow() { this.DataContext = new MainViewModel(); } Then in the Xaml I am attempting to bind the ItemsSource of a ListBox to that ProjectList property. Binding just ItemsSource like so doesn't work: <ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." /> But if I first rebase the DataContext this works: <ListBox DataContext="{Binding ProjectList}" ItemsSource="{Binding}" ItemTemplate="..." /> Shouldn't the first method work properly? What am I doing wrong?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >