2012-11-19 2 views
0

모델과 바인딩하려는 명령 단추 목록이 있습니다 (입력 포함). 버튼의 텍스트 상자를 어딘가에 바인딩하고 싶습니다 (viewmodel 참조).TextBox.TextProperty를 모델에서 Binding 유형의 속성에 바인딩

다음 코드는 내가 시도한 것이며 실패한 것입니다. 모델에 바인딩을 설정 한 다음 컨트롤에 바인딩 할 수 있습니까?

다른 말로하면 나는 어리석은 방법을 시도하고 있습니까?

보기 :

<ToolBar Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="0" ItemsSource="{Binding SelectedTab.Commands}" Height="34"> 
    <ToolBar.Resources> 
     <DataTemplate DataType="{x:Type model:ZoekCommandButtons}"> 
      <Button Command="{Binding Command}" ToolTip="{Binding Tooltip}" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"> 
       <StackPanel Orientation="Horizontal"> 
        <Image Source="{Binding Image, Converter={StaticResource ImageConv}}" Height="16" Width="16"></Image> 
        **<TextBox Width="100" Text="{Binding Text}">** 
         <TextBox.InputBindings> 
          <KeyBinding Gesture="Enter" Command="{Binding Command}"></KeyBinding> 
         </TextBox.InputBindings> 
        </TextBox> 
       </StackPanel> 
      </Button> 
     </DataTemplate> 
    </ToolBar.Resources> 
</ToolBar> 

모델 :

public class ZoekCommandButtons : BaseModel, ICommandItem 
    { 
     private string _header; 
     private string _image; 
     private bool _isEnabled; 
     private Visibility _isVisible; 
     private ICommand _command; 
     private string _tooltip; 
     private Binding _text; 


     public Binding Text 
     { 
      get { return _text; } 
      set { _text = value; OnPropertyChanged("Text"); } 
     } 
(etc) 

뷰 모델 :

Commands.Add(new ZoekCommandButtons() 
    { 
     Image = "search.png", 
     IsEnabled = true, 
     **Text = new Binding { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(UserControl), 1), Path = new PropertyPath("FilterText") },** 
     Command = FilterCommand, 
     Tooltip = "Zoeken", 
     Header = "Zoeken" 
    }); 

답변

3

우선, 나는 것 하지 좋습니다 뷰 모델 속성으로 Binding을 노출시키는 단계; 이 특별한 경우에는 중첩 된 ViewModels를 가지고있는 것처럼 내게 들려요.이 접근법은 훨씬 더 적합합니다. 즉, "Commands"속성을 가진 "MamaViewModel"속성이 있습니다.이 속성은 " CommandButtonViewModels "...

그건 내가 반복해야하지만 ... 당신이 는,이 작업을 수행 할 수 있다고 말했다, 좋아, 당신 아마해야 하지; 당신이 누락 된 것은 "가치를 제공하기 위해 바인딩을 평가할 무언가"입니다. 여기 당신에게 제공하는 클래스입니다 그 :

public class DontDoThisViewModel 
{ 
    public Binding TextBinding {get; set;} 
    public string Text 
    { 
     get 
     { 
      return BindingEvaluator.Evaluate(TextBinding) as string; 
     } 
    } 
} 

해야하는 작업 ... 여기에 내가 LINQPad 함께 던졌다 테스트 응용 프로그램은 다음과 같습니다 :

같은 뷰 모델 정의 무언가와 결합, 즉

public static class BindingEvaluator 
{ 
    // need a DP to set the binding to 
    private static readonly DependencyProperty PlaceholderProperty = 
     DependencyProperty.RegisterAttached("Placeholder", typeof(object), typeof(DependencyObject), new UIPropertyMetadata(null)); 

    // Evaluate a binding by attaching it to a dummy object/property and evaluating the property value 
    public static object Evaluate(Binding binding) 
    { 
     var throwaway = new DependencyObject(); 
     BindingOperations.SetBinding(throwaway, PlaceholderProperty, binding); 
     var retVal = throwaway.GetValue(PlaceholderProperty); 
     return retVal; 
    } 
} 

다시

void Main() 
{ 
    var wnd = new Window() { Title = "My window" }; 
    var text = new TextBlock(); 
    text.Text = "Hopefully this shows the window title..."; 
    text.SetBinding(TextBlock.TextProperty, new Binding("Text")); 
    wnd.Content = text; 
    var vm = new ViewModel(); 
    var vmBinding = new Binding("Title"); 
    vmBinding.Source = wnd; 
    vm.TextBinding = vmBinding; 
    wnd.DataContext = vm; 
    wnd.Show(); 
} 

, 나는 강하게이 작업을 수행하지 당신에게 를 추천합니다 ...하지만 난 호기심, 그래서 방법을 생각해 내야했다. ;)

+0

의견을 보내 주셔서 감사합니다. 나는 정말로 필요한 것을 성취 할 다른 방법을 찾았고 Binding을 사용하여 Binding하지 않았습니다. 그러나 멋진 방법을 찾았습니다. –

0

좋아. 나는 똑바로 생각하고 있지 않았다.

Model의 Text 속성을 string으로 변경하고이 속성을 사용하여 명령을 처리했습니다.

(가 ... 어떻게 든 모델에 바인딩 설정 좋을 것이다 있지만)