开发者

Bind TextBlock in DataTemplate (resource) to Content of checked radio button

I have a TextBlock in resource data template:

<DataTemplate x:Key="MyDataTemplate" ItemsSource="{Binding MySource}">
    <TextBlock x:Name="MyText" Text="{Binding ???}" />
</DataTemplate>

that I want to bind with Content of checked radio button:

<RadioButton GroupName="MyGroup" Content="Code" />
<RadioButton GroupName="MyGroup" Content="Description" />

if Code radio button is selected, t开发者_Go百科hen I want the text become Text={Binding Code}.

Please help, thank you.


Assuming this is backed by a viewmodel, you would set up your viewmodel thusly:

bool isCodeChecked;
public bool IsCodeChecked 
{ 
    get { return isCodeChecked; }
    set
    {
        if(value == isCodeChecked) return;
        isCodeChecked = value;
        // raise notification that ***MyText*** property has changed (INotifyPropertyChanged interface)
    }

public string MyText 
{
    get { return IsCodeChecked ? "Code" : "Description"; }
}

Then set up your XAML:

<RadioButton GroupName="MyGroup" Content="Code" IsChecked="{Binding IsCodeChecked, Mode=OneWayToSource}" />

<DataTemplate x:Key="MyDataTemplate" ItemsSource="{Binding MySource}">
     <TextBlock x:Name="MyText" Text="{Binding MyText}" />
</DataTemplate>

The binding on the CheckBox will cause the boolean property on the viewmodel to be updated, which in turn will notify the textbox to update its bound value.


I created 2 DataTamplate in resources, and I switch my TreeView's ItemTemplate from code behind

if (ViewByCodeRadioButton.IsChecked == true)
    MyTreeView.ItemTemplate = Resources["MyDataTemplateCode"] as DataTemplate;
else
    MyTreeView.ItemTemplate = Resources["MyDataTemplateDesc"] as DataTemplate;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜